Accepting PHP variables but not in SQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
webphotogeek
Forum Newbie
Posts: 18
Joined: Sun Jul 04, 2010 12:11 pm

Accepting PHP variables but not in SQL

Post 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");  

?>
Last edited by Benjamin on Sun Jul 04, 2010 12:26 pm, edited 2 times in total.
Reason: Added [syntax=php] tags.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Accepting PHP variables but not in SQL

Post 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) . "'"; 
webphotogeek
Forum Newbie
Posts: 18
Joined: Sun Jul 04, 2010 12:11 pm

Re: Accepting PHP variables but not in SQL

Post by webphotogeek »

That was it! Thank you and thanks for the information on the mysql_real_escape_string() function.

- Steve
Post Reply