Page 1 of 1

Accepting PHP variables but not in SQL

Posted: Sun Jul 04, 2010 12:22 pm
by webphotogeek
I have a simple SQL code that is not working, but I have confirmed that the variables are being captured from the form ($city = $_POST["city"]; echo $city;). If I force a constant in - WHERE City ='ny' , it works, but not when I use a variable. It's been a while since I've used PHP and MySQL. What am I missing here?

Here's the code:

Code: Select all

<?php 

	$city = $_POST["city"]; echo $city; 

	$link = mysql_connect("localhost", "xxxxxxxx", "xxxxxxx") or die ("Access To DB Error"); // Sets up the link = server, username and pw.
	mysql_select_db("rr_test", $link) or die ("DB not selected"); 

	$Res = "SELECT * FROM general WHERE City = $city"; 
	$Results = mysql_query($Res) or die ("No Data Selected");  

?>

Re: Accepting PHP variables but not in SQL

Posted: Sun Jul 04, 2010 12:28 pm
by Benjamin
Strings need to be quoted when used in queries. Also, you need to escape the data for it to work correctly all the time and for security.

Code: Select all

$Res = "SELECT * FROM general WHERE City = '" . mysql_real_escape_string($city) . "'"; 

Re: Accepting PHP variables but not in SQL

Posted: Sun Jul 04, 2010 10:13 pm
by webphotogeek
That was it! Thank you and thanks for the information on the mysql_real_escape_string() function.

- Steve