Page 1 of 1

cant pass a variable to a mysql_query

Posted: Sat Jun 07, 2008 11:05 am
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);
?>

Re: cant pass a variable to a mysql_query

Posted: Sat Jun 07, 2008 11:13 am
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.