Validating form data - stop MySQL injection

I am trying to get this form to work properly and right now it seems to be working.

However I was told I needed to validate data that is being input so as to be protected by a MySQL injection - using this mysql_real_escape_string()

Not quite sure how to insert the code properly - need some pointers on that one.

Also I have the form on my WAMP server and each time I load the form it has the previous test data that I input - can this be solved by issuing a Session?

There are a lot of session functions and I am not sure which one would satisfy my purposes.
session_id
session_start ?? Not quite sure on this one.

Also, if anyone would like to make suggestions about how to make this form 100% secure or better coding - I am up for learning PHP which is quite new to me.


<form action="update.php" method="post">

<p>City:<br/>
<input type="text" name="city" size="30" /></p>

<p>Property Type:<br/>
<select name="type">
<option value="Single Family Home">Single Family Home</option>
<option value="Condo">Condo</option>
<option value="Duplex">Duplex</option>
<option value="Multi-Unit">Multi-Unit</option>
<option value="Rental">Rental</option>
</select></p>


<p> Radius:<br/>
<select name="radius">
<option value="5 miles">5</option>
<option value="10 miles">10</option>
<option value="15 miles ">15</option>
<option value="20 miles">20</option>
<option value="25 miles">25</option>
</select></p>


<p> Price Range:<br/>
<select name="price">
<option value="under $200,000">Under $200,000</option>
<option value="$200,000 - $300,000">$200,000 - $300,000</option>
<option value="$300,001 - $400,000">$300,001 - $400,000</option>
<option value="$400,001 - $500,000">$400,001 - $500,000</option>
<option value="Over $500,000">Over $500,000</option>
</select></p>


<p> Number of Bedrooms:<br/>
<select name="bedrooms">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5 or more</option>
</select></p>

<p> Number of Bathrooms:<br/>
<select name="bathrooms">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5 or more</option>
</select></p>


<p> Garage Parking Preference:<br />
<select name="parking">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</p><br />  

<p>Please give some details on your ideal property.  This can include features of your ideal home including near an elementary school,<br/> 
parks, Close to Shopping. Feel free to describe anything you would like in the home that has not been covered.<br />
<textarea name="details" rows="20" cols="100" wrap="virtual" /></textarea></p>


<p>First name:<br/>
<input type="text" name="firstname" size="40" /></p>

<p>Last name:<br/>
<input type="text" name="lastname" size="40" /></p>
     
<p>email address:<br/>
<input type="text" name="email" size="40" /></p>

<p>Phone Number<br/>
<input type="text" name="phone" size="40" /></p>
     

     
<p><input type="submit" value="Send feedback" /></p>

</form>



//PHP 

<?php 

error_reporting(E_ALL ^ E_NOTICE); 
?>
<?php 
$city = $_POST['city'];
$radius = $_POST['radius'];
$type = $_POST['type'];
$price = $_POST['price'];
$bedrooms = $_POST['bedrooms'];
$bathrooms = $_POST['bathrooms'];
$parking = $_POST['parking'];
$details = $_POST['details'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];

// 1. Create a database connection
	$connection = mysql_connect("localhost", "root", "maven777");
	if(!$connection){
		die("Database connection failed: " .mysql_error());
	}

// 2. Select a database to use
	$db_select = mysql_select_db("homesloans", $connection);
	if(!$db_select){
		die("Database selection failed: " .mysql_error());
	}
	
	$query="INSERT INTO leads (leadid, city, radius, type, price, bedrooms,
	bathrooms, parking, details, firstname, lastname, email, phone)
	
	VALUES('NULL', '[$city]', '[$radius]', '[$type]', '[$price]', '[$bedrooms]',
			'[$bathrooms]', '[$parking]', '[$details]', '[$firstname]', '[$lastname]', '[$email]', '[$phone]')";
	
	mysql_query($query) or die ('Error updating database');
	
	echo "Database Successfully Updated."; 
	
	
	 
?>

a concatenation dot? like that?

	$query = "INSERT [INTO] leads [(leadid, city, radius, type, price, bedrooms,
	bathrooms, parking, details, firstname, lastname, email, phone)]" . 
	
	VALUES ('NULL', '$city', '$radius', '$type', '$price', '$bedrooms',
    '$bathrooms', '$parking', '$details', '$firstname', '$lastname', '$email', '$phone');
  1. mysql_real_escape_string() is an output function designed fore escaping content in old style database accesses thatmight be confused with the query itself. It has NOTHING to do with security or validation.

  2. If you use prepare and bind statements either through PDO or using the more modern mysqli_ calls instead of the antiquated mysql_ ones then you don’t need to escape the data because it is kept completely separate.

  3. To secure your application you need to validate the $_POST valiues BEFORE you assign them to internal variable names.

eg.

$city = validateCity($_POST[‘city’]);

where the validateCity function validates that the city foeld contains something that is valid for that field.

If you don’t perform the validation FIRST before doing anything else then your entire application is tainted and potentially subject to attacks of various sorts. There are lots of different types of security hole and those that relate to sql injection are only a small percentage of the total but by validating properly at the start you protect against all security attacks.

yes, and you can remove the brackets around INTO and the column names.

I’ve only seen used in this context when describing syntax for something, not in the actual statement.

that’s because in the line above line 51 you have a semi-colon at the end instead of a concatenation dot

$query = "INSERT [INTO] leads [(leadid, city, radius, type, price, bedrooms,
    bathrooms, parking, details, firstname, lastname, email, phone)]"[B][COLOR=Red];[/COLOR][/B]

and what are the around INTO for?

Didn’t catch that on my way through your code. It is treating VALUES(..., ...) as a function call, and of course since there is no function named VALUES(), it is going to fail and throw you an error.

This what I have and I keep getting the error message for being able to put the data in the DB

webdev1958 Said “You have syntax errors in your $query sql statement.” and I don’t see it - when I change it from what I have I get a syntax error in dreamweaver.

Very frustrated with probably an easy solution - just one I don’t know yet…

<?php 

error_reporting(E_ALL ^ E_NOTICE); 
?>
<?php
// make sure the form has actually been submitted . . .
if( strtolower($_SERVER['REQUEST_METHOD']) === 'post' ) { 
	
	
	// 1. Create a database connection
	$connection = mysql_connect("localhost", "root", "maven777");
	if(!$connection){
		die("Database connection failed: " .mysql_error());
	}

	// 2. Select a database to use
	$db_select = mysql_select_db("homesloans", $connection);
	if(!$db_select){
		die("Database selection failed: " .mysql_error());
	}
	$radius = mysql_real_escape_string($_POST['radius']);
	$type = mysql_real_escape_string($_POST['type']);
	$price = mysql_real_escape_string($_POST['price']);
	$bedrooms = mysql_real_escape_string($_POST['bedrooms']);
	$bathrooms = mysql_real_escape_string($_POST['bathrooms']);
	$parking = mysql_real_escape_string($_POST['parking']);
	$city = mysql_real_escape_string($_POST['city']);
	$details = mysql_real_escape_string($_POST['details']);
	$firstname = mysql_real_escape_string($_POST['firstname ']);
	$lastname = mysql_real_escape_string($_POST['lastname']);
	$email = mysql_real_escape_string($_POST['email']);
	$phone = mysql_real_escape_string($_POST['phone']);

	$query = "INSERT [INTO] leads [(leadid, city, radius, type, price, bedrooms,
	bathrooms, parking, details, firstname, lastname, email, phone)]
	
	VALUES ('NULL', '$city', '$radius', '$type', '$price', '$bedrooms',
	'$bathrooms', '$parking', '$details', '$firstname', '$lastname', '$email', '$phone')";

	mysql_query($query) or die ('Error updating database - what?');

	echo "Database Successfully Updated."; // not necessarily. The only way to know for sure is to check  that mysql_affected_rows() > 0
}
?>

Here’s whats driving you nuts: :slight_smile:

First of all, you have an opening quote on your query statement ($query = [COLOR="red"]"[/COLOR]INSERT [INTO] leads [(leadid, city, radius, type, price, bedrooms, bathrooms, parking, details, firstname, lastname, email, phone)]) but not a closing one. You also need a semicolon after that.

Then you have a stray quote on this line: VALUES ('NULL', '$city', '$radius', '$type', '$price', '$bedrooms', '$bathrooms', '$parking', '$details', '$firstname', '$lastname', '$email', '$phone')[COLOR="Red"]"[/COLOR];.

Here is the full revised code:

<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<?php
// make sure the form has actually been submitted . . .
if( strtolower($_SERVER['REQUEST_METHOD']) === 'post' ) { 
	
	
	// 1. Create a database connection
	$connection = mysql_connect("localhost", "root", "maven777");
	if(!$connection){
		die("Database connection failed: " .mysql_error());
	}

	// 2. Select a database to use
	$db_select = mysql_select_db("homesloans", $connection);
	if(!$db_select){
		die("Database selection failed: " .mysql_error());
	}
	$radius = mysql_real_escape_string($_POST['radius']);
	$type = mysql_real_escape_string($_POST['type']);
	$price = mysql_real_escape_string($_POST['price']);
	$bedrooms = mysql_real_escape_string($_POST['bedrooms']);
	$bathrooms = mysql_real_escape_string($_POST['bathrooms']);
	$parking = mysql_real_escape_string($_POST['parking']);
	$city = mysql_real_escape_string($_POST['city']);
	$details = mysql_real_escape_string($_POST['details']);
	$firstname = mysql_real_escape_string($_POST['firstname ']);
	$lastname = mysql_real_escape_string($_POST['lastname']);
	$email = mysql_real_escape_string($_POST['email']);
	$phone = mysql_real_escape_string($_POST['phone']);

	$query = "INSERT [INTO] leads [(leadid, city, radius, type, price, bedrooms,
	bathrooms, parking, details, firstname, lastname, email, phone)]";
	
	VALUES ('NULL', '$city', '$radius', '$type', '$price', '$bedrooms',
	'$bathrooms', '$parking', '$details', '$firstname', '$lastname', '$email', '$phone');

	mysql_query($query) or die ('Error updating database - what?');

	echo "Database Successfully Updated."; // not necessarily. The only way to know for sure is to check  that mysql_affected_rows() > 0
}
?>

Fatal error: Call to undefined function VALUES() in C:\wamp\www\homesloans\update.php on line 51

 

Line 51 --> VALUES ('NULL', '$city', '$radius', '$type', '$price', '$bedrooms',
    '$bathrooms', '$parking', '$details', '$firstname', '$lastname', '$email', '$phone');
 
    mysql_query($query) or die ('Error updating database - what?');

Keep in mind mysql_real_escape_string is for strings, it will do nothing to escape SQL Injection via hex on numerical values for example. For numbers just cast as the proper type such as:

$price = (float)$price;
$someId = (int)$id;

Get this error - don’t quite understand how to fix.

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\homesloans\update.php on line 48

<?php 

error_reporting(E_ALL ^ E_NOTICE); 
?>
<?php 
$city = $_POST['city'];
$radius = $_POST['radius'];
$type = $_POST['type'];
$price = $_POST['price'];
$bedrooms = $_POST['bedrooms'];
$bathrooms = $_POST['bathrooms'];
$parking = $_POST['parking'];
$details = $_POST['details'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];

// 1. Create a database connection
	$connection = mysql_connect("localhost", "root", "maven777");
	if(!$connection){
		die("Database connection failed: " .mysql_error());
	}

// 2. Select a database to use
	$db_select = mysql_select_db("homesloans", $connection);
	if(!$db_select){
		die("Database selection failed: " .mysql_error());
	}
	
	$query="INSERT INTO leads (leadid, city, radius, type, price, bedrooms,
	bathrooms, parking, details, firstname, lastname, email, phone),
	
	$city = mysql_real_escape_string($_POST['city']),
	$details = mysql_real_escape_string($_POST['details']),
	$firstname = mysql_real_escape_string($_POST['firstname ']),
	$lastname = mysql_real_escape_string($_POST['lastname']),
	$email = mysql_real_escape_string($_POST['email'])
	$phone = mysql_real_escape_string($_POST['phone']),

	
	
	VALUES('NULL', '[$city]', '[$radius]', '[$type]', '[$price]', '[$bedrooms]',
			'[$bathrooms]', '[$parking]', '[$details]', '[$firstname]', '[$lastname]', '[$email]', '[$phone]')";
			
			
			
	
	mysql_query($query) or die ('Error updating database');
	
	echo "Database Successfully Updated."; 
	
	
	 
?>

which is line 48?

48 $city = mysql_real_escape_string($_POST[‘city’]),

You have syntax errors in your $query sql statement. Have a look through the link I posted where it shows you how to use mysql_real_escape_string. There are lots of other examples on how to use mysql_real_escape_string() in sql statements on the www as well if you google it.

The online php manual is usually a good place to start - [URL=“http://php.net/manual/en/function.mysql-real-escape-string.php”]mysql_real_escape_string()