Getting error when passing variables

Hi,

Im new to php and mysqli and I’m struggling to find the error in this line of code:

[php]$result2 = mysqli_query($dbconn,$sql2) or die('Could not look up SHOWTYPE L25; ’ . mysqli_error($dbconn));[/php]

There may not be anything wrong but when the page loads I’m getting the error:
Could not look up SHOWTYPE L25; You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘s Show’’ at line 1

and I’m struggling to track it down.

the whole code can be viewed here:

Thanks for any help.

Carl.

Your query is vulnerable to SQL injection attacks, which you have proven by sending in a string with a single quote that results in invalid SQL syntax. Which sadly still is the number one method of hacking websites and services.

SELECT showtypeid FROM showtypes WHERE showtype='".$showtype."'

inject ->

$showtype = "Something's Show"

resulting in ->

SELECT showtypeid FROM showtypes WHERE showtype='Something's Show'

[hr]

You should always use parameterized / prepared queries (using placeholders instead of directly injecting parameters) to avoid this.

http://php.net/manual/en/mysqli.prepare.php

Thanks for the reply.

by placeholders, you mean ?, ?, ?,

Ive seen these but they frighten me ;D

I’ve literally only been using php for a week. LOL

yes, mysqli uses unnamed placeholders. this has multiple advantages

  1. you can prepare a query which is then compiled by mysql
    if you then run the query multiple times (ie while iterating over a list of users), it will be precompiled and faster.

  2. the parameters are passed to the mysql engine separately from the query
    in effect mysql knows the potentially malicious parameters are not part of the original query, which means a hacker can not break out of the parameter to execute some arbitrary sql commands.

If you want to get on the right track with PHP I suggest you head over to http://www.phptherightway.com/ and have a look. It’s a great resource on how to properly use PHP today.

Thanks so much Jim, thats most helpful, and it’s not as scary as I thought.

Am i right in thinking that once you’ve created and executed the $stmt then that information is secure to display on the webpage without worry of this SQL Injection stuff.

Where can injections be actioned?

Carl.

SQL injections are possible when you input user data (from a form, from the url, from the browser, etc) directly into a query. Using placeholders and passing the data in separately avoids this entirely.

[hr]

When outputting data you should make sure to properly escape the data, so potential malicous scripts don’t get executed. This is called XSS (Cross Site Scripting).

Imagine I enter this as my display name:

jimlei<script src="http://evil.com/nasty.js"></script>

If you just save that into the database, and later display it on a page (like my profile page), any user that visits my profile page will execute my evil script. Which can capture cookies, redirect the user to another page, inject frames or java applets that try to load viruses to the users computer, etc etc.

ok I’ve not even heard of XSS, but ill certainly implement it.

Should it be used every time query info is displayed?

also on a side note, i thought this was correct syntax:

[php]<?php

		$pullclients = $dbconn->prepare("SELECT clientid, company, email, telno FROM clients");
		$pullclients->bind_param('dsss', $getclients);
		$pullclients->bind_result($clientid, $company, $email, $telno);
		$pullclients->execute();
		$pullclients->store_result();[/php]

but although the query runs and the information outputs ok i get the error:

mysqli_stmt::bind_param(): Number of elements in type definition string doesn’t match number of bind variables etc

i though from what I’ve read, you match the param(‘XXXX’ to the number of elements in the bind_result?

every time you output data you aren’t 100% sure is safe. Which is why most template engines let you turn on escaping of all output data, just to be sure.

[hr]

The param string (‘dsss’) should match the params (the ones that will replace the placeholders), in this query you don’t have any params so you can skip this line. You can bind the results though if you want.

aaah i think i get ya!

Thanks for all your help.

I have no doubt ill be back very soon LOL

Can anyone tell me if by using bootstrap to output data to a table, does this automatically make it XSS friendly?

Ive been told does by someone but not sure if this is correct.

Carl.

No, Bootstrap is just a UI framework with mainly CSS and some JS features (like modals and tooltips)

so this code is still not XSS friendly? It just outputs a table from a database.

[php]<?php require_once('Connections/db_main.php'); ?>

Theatre Management System | Clients

FULL CLIENT LIST

Below is a complete list of clients listed by Company Name in alphabetical order. You can also edit your client information from this screen by clicking on the "Edit" link at the end of each row, or by clicking the actual Company name.

      <?php 

$getclients = “SELECT * FROM clients”;

$result = mysqli_query($dbconn, $getclients)or die(mysqli_error(“Could Not Retrieve Clients From Database:”));

echo “

”;
echo “









”;

while($row = mysqli_fetch_array($result)) {
$clientid = $row[‘clientid’];
$company = $row[‘company’];
$fname = $row[‘fname’];
$sname = $row[‘sname’];
$address1 = $row[‘address1’];
$address2 = $row[‘address2’];
$town = $row[‘town’];
$county = $row[‘county’];
$pcode = $row[‘pcode’];
$telno = $row[‘telno’];
$email = $row[‘email’];

echo "<tr>
		<td width=auto>".$clientid."</td>
		<td>".$company."</td>
		<td>".$fname."</td>
		<td>".$sname."</td>
		<td>".$address1."</td>
		<td>".$address2."</td>
		<td>".$town."</td>
		<td>".$county."</td>
		<td>".$pcode."</td>
		<td>".$telno."</td>
		<td>".$email."</td>
	  </tr>";

}

echo "

ID Client Name First Name Last Name Address Address 2 Town County Post Code Contact no Email
";
mysqli_close($dbconn);
?>
          </div>
        </div>
      </div>
    </div>
   
    
     

    <div id="footer" >
    <div class="left">
      <div class="right">
        <div class="footerlink">
           <p class="lf">Copyright &copy; 2015 Carl Young <a href="#">Theatre Management System</a> - All Rights Reserved</p>
          <p class="rf">Version: Beta 1.0.1</p>
          <div style="clear:both;"></div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php //mysql_free_result($rs_clientfulllist); ?> [/php]

Add this line of code to the form that would add data to your table.

[php][/php]

Astonecipher

I get what you’re saying but I cannot understand that if the code which WRITES the data to the database is XSS friendly, why would you need to sanitise the data being displayed.

I’m just trying to get my head around why you would need to sanitise the data twice?

Carl.

When you insert the data in the database you need to make sure the user isn’t able to manipulate it to perform an SQL injection attack (ie: run malicious sql commands)

When you output data, either to the user in ie html or javascript, you need to make sure the user isn’t able to manipulate it to perform an XSS attack.

SQLi and XSS are two completely separate attacks - and you need to safe guard against both

ok I’m almost at the point of giving up.

Ive googled and youtube until my eyes are sore but still cannot stop my page passing that example to my database and the database outputting it then the page loads.

my syntax for form data is:

[php]$company = mysqli_real_escape_string($dbconn, ($_POST[‘company’]));[/php]

It throws no error up when inserting the records

but still does not strip the data as you can see here:

http://imgur.com/QnbEYCe

Any help without sending me off to do even more googling, lol.

Sorted it. I think.

I have now syntax it as this:

[php]$clientid = htmlentities($_POST[‘clientid’]);
mysqli_real_escape_string($dbconn, $clientid);[/php]

Does that look a better way of doing it or is there an even better way?

Carl.

Can you post the entire code you are working with now (query, mysqli-stuff, etc). To be sure we’re working on the same thing.

But no, you should not use either htmlentities or mysqli_real_escape_string before inserting data into the database.

You should use the placeholder and just bind the parameter to the query.

Trivia:
Using placeholders in queries replaced the old “real escape string” method of doing things - over ten years ago.
which replaced the “escape string” function, that didn’t really work (hence the “real” new one)

Here’s the entire code.

Its awfully messy as I’ve not yet tidied it up. Hope you can make sense of it:

[php]<?php
$hostname_db_main = “localhost”;
$username_db_main = “tmsonlin_main”;
$password_db_main = “**************”;
$database_db_main = “tmsonlin_main”;

$dbconn = mysqli_connect($hostname_db_main,$username_db_main,$password_db_main,$database_db_main) or die ('ERROR: Could not connect to database!');
$connection = $dbconn;

if (isset($_POST[‘submitted’])) {
include(‘Connections/db_main.php’);
// SET UP POST DATA VARIABLES
$clientid = htmlentities($_POST[‘clientid’]);
mysqli_real_escape_string($dbconn, $clientid);
$fname = htmlentities($_POST[‘fname’]);
mysqli_real_escape_string($dbconn, $fname);
$sname = htmlentities($_POST[‘sname’]);
mysqli_real_escape_string($dbconn, $sname);
$company = htmlentities($_POST[‘company’]);
mysqli_real_escape_string($dbconn, $company);
$address1 = htmlentities($_POST[‘address1’]);
mysqli_real_escape_string($dbconn, $address1);
$address2 = htmlentities($_POST[‘address2’]);
mysqli_real_escape_string($dbconn, $address2);
$town = htmlentities($_POST[‘town’]);
mysqli_real_escape_string($dbconn, $town);
$county = htmlentities($_POST[‘county’]);
mysqli_real_escape_string($dbconn, $county);
$pcode = htmlentities($_POST[‘pcode’]);
mysqli_real_escape_string($dbconn, $pcode);
$telno = htmlentities($_POST[‘telno’]);
mysqli_real_escape_string($dbconn, $telno);
$email = htmlentities($_POST[‘email’]);
mysqli_real_escape_string($dbconn, $email);

//CREATE SQL PREPARED STATEMENT
$mysqli = new mysqli('localhost','tmsonlin_main','moosh!man!000','tmsonlin_main');
$stmt = $mysqli->stmt_init();
			if (!stmt) {
			echo "Init Failed: Error Code L22";
			} else {
$insert="INSERT INTO clients (clientid, fname, sname, company, address1, address2, town, county, pcode, telno, email) 
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
			
			if ($stmt->prepare($insert)) {
				$stmt->bind_param('issssssssss', $clientid, $fname, $sname, $company, $address1, $address2, $town, $county, $pcode, $telno, $email);
				$stmt->execute();
				$stmt->close();
				echo "Customer Added To Database";
				
			} else {
				echo "PREPARE FAILED";
			}
		}
			$mysqli->close();

}

?>

Theatre Management System | Clients

ADD NEW CLIENT**

First Name :
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Surname :</label></div>
                                                    <div class="col-lg-6"><input type="text" id="sname" name="sname" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>

                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Company Name :</label></div>
                                                    <div class="col-lg-6"><input type="text" name="company" id="company" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>

                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Address 1 :</label></div>
                                                    <div class="col-lg-10"><input type="text" name="address1" id="address1" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>

                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Address 2 :</label></div>
                                                    <div class="col-lg-10"><input type="text" name="address2" id="address2" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>

                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Town / City :</label></div>
                                                    <div class="col-lg-3"><input type="text" name="town" id="town" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">County :</label></div>
                                                    <div class="col-lg-3"><input type="text" name="county" id="county" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>

                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Post Code :</label></div>
                                                    <div class="col-lg-3"><input type="text" name="pcode" id="pcode" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Contact Number :</label></div>
                                                    <div class="col-lg-3"><input type="text" name="telno"  id="telno" class="form-control" ></input></div>
                                                </div>
                                            </div>
                                            <p></p>

                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"><label class="label">Email Address :</label></div>
                                                    <div class="col-lg-10"><input type="email" name="email"  id="email" class="form-control" required ></input></div>
                                                </div>
                                            </div>
                                            
                                            <p></p>
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="col-lg-2"></div>
                                                    <div class="col-lg-2"> <input type="submit" value="Add New Client" class="btn btn-success form-control"></input></input></div>
                                                </div>
                                            </div>
                                           
                                            <input type="hidden" name="clientid" value="" />

                                        </form></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="content">

                        <p> 
<?php // DISPLAY RECORD INSERTION CONFIRMATION ?>
                        </p>
                    </div>
                    <div id="footer">
                        <div class="left">
                            <div class="right">
                                <div class="footerlink">
                                    <p class="lf">Copyright &copy; 2015 Carl Young <a href="#">Theatre Management System</a> - All Rights Reserved</p>
                                    <p class="rf">Version: Beta 1.0.1</p>
                                    <div style="clear:both;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script type="text/javascript"> Cufon.now();</script>
        <!-- END PAGE SOURCE -->
</body>
[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service