I am a newbie in MySQL and PHP. I have a HTML form where I would like to pass 1 variable from to my PHP code and then run a query on my database for the record that holds that variable under the column 'Serial'. I can run it fine when I hard code the 'serial' that I want to look up but when I try with the variable I get an error.
Any help would greatly be appreciated! Or a better way to do this.
Here is my error: Unknown column 'amg002' in 'where clause'
Here is my code;
$serial= $_POST['Serial'];
echo $serial;
//Connect To Database
$link = mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
echo "Connected to MySQL<br />";
//Select the database - 'SiteInfo'
// Collects data from "SiteInfo" table
//****This is where I am running into the error***
$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial;
// This works!!!
//$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ="amg002";';
$data = mysql_query($sql)
or die(mysql_error());
// puts the "SiteInfo" info into the $info array
$info = mysql_fetch_array( $data );
//Print out the contents of the entry
echo "Site Name: ".$info['SiteName'] . "<br /";
Print "Serial Number: ".$info['Serial'] . "<br />";
Print "Location: ".$info['Location'] . "<br />";
// Close the database connection
mysql_close($link);
echo "Connection Closed. <br />";
I agree its a quote issue, but here is how my code would look.
$sql = 'SELECT * FROM SiteInfo WHERE Serial = "' . $serial . '"';
or
$sql = "SELECT * FROM 'SiteInfo; WHERE 'Serial' = \"$serial\"";
Looks like a quote issue:
$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial.';
should be
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` ='".$serial."'";
It means your variable:
$_POST['Serial']
is coming empty. You need to run your code if it isn't empty by checking it via isset
like this:
if (isset( $_POST['Serial'])) {
$serial= $_POST['Serial'];
// your rest of the code
}
Also if Serial
is string and not a number, you need to put it in quotes, use below query:
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'";
You can also check out what does your query come up like:
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'";
echo $sql;
exit;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.