cant pass a variable to a mysql_query

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
rswitzer
Forum Newbie
Posts: 1
Joined: Sat Jun 07, 2008 10:52 am

cant pass a variable to a mysql_query

Post by rswitzer »

Help! Im just learning PHP. I'm trying to write a script that receives a variable "NAME" from a html form,
which is a field in a mysql database.
my script receives 'NAME' as indicated by printing it out.(echo $name) BUT,
all I get from the mysql_query are warnings that the arguments supplied are not valid. When I use a real field name for the
query such as ".....WHERE 'Holly'..." the script runs fine and returns all data sucessfully

Why cant I pass a $name to the mysql_query ???
Thanks in advance,
Bob in San Diego

script:
<?php
mysql_connect("localhost", "username", "pw") or
die("Could not connect: " . mysql_error());
$name = strip_tags(trim($_POST['NAME']));
echo $name;
mysql_select_db("test");

$result = mysql_query("SELECT NAME, State, COLOR FROM testa WHERE NAME = $name");
mysql_real_escape_string($name);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
printf("ID: %s Name: %s COLOR: %s", $row["NAME"], $row["State"], $row[COLOR]);


mysql_free_result($result);
?>
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: cant pass a variable to a mysql_query

Post by Benjamin »

Changed it up a bit:

Code: Select all

 
mysql_connect("localhost", "username", "pw") or die("Could not connect: " . mysql_error());
mysql_select_db("test");
 
$name = mysql_real_escape_string(strip_tags(trim($_POST['NAME'])));
echo $name;
 
 
$resource = mysql_query("SELECT NAME, State, COLOR FROM testa WHERE NAME = '$name'");
 
if (!is_resource($resource))
{
    echo mysql_error();
    exit();
}
 
$row = mysql_fetch_assoc($resource);
printf("ID: %s Name: %s COLOR: %s", $row["NAME"], $row["State"], $row['COLOR']);
 
mysql_free_result($result);
 
In your original code there were a few issues.

1. Strings need to be quoted in database queries
2. You were calling mysql_real_escape_string AFTER the query.
3. There were no tests to check if the query was successful.
Post Reply