在WHERE子句中使用变量

时间:2012-05-29 17:00:28

标签: php mysql

我是MySQL和PHP的新手。我有一个HTML表单,我希望将1个变量传递给我的PHP代码,然后在我的数据库上运行一个查询,以获取该列下的变量' Serial'。当我对“序列号”进行硬编码时,我可以正常运行。我想查找,但当我尝试变量时,我得到一个错误。

非常感谢任何帮助!或者更好的方法来做到这一点。

这是我的错误:Unknown column 'amg002' in 'where clause'

这是我的代码;

$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 />";

3 个答案:

答案 0 :(得分:1)

我同意它的引用问题,但这是我的代码的样子。

  $sql = 'SELECT * FROM SiteInfo WHERE Serial = "' . $serial . '"';

  $sql = "SELECT * FROM 'SiteInfo; WHERE 'Serial' = \"$serial\"";      

答案 1 :(得分:0)

看起来像报价问题:

 $sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial.'; 

应该是

 $sql = "SELECT * FROM `SiteInfo` WHERE `Serial` ='".$serial."'"; 

答案 2 :(得分:0)

这意味着你的变量:

$_POST['Serial']

空洞。如果代码不为空,则需要通过isset检查代码,如下所示:

if (isset( $_POST['Serial'])) {
  $serial= $_POST['Serial'];

  // your rest of the code
}

如果Serial是字符串而不是数字,则需要将其放在引号中,使用以下查询:

$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'"; 

您还可以查看您的查询结果如何:

$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'"; 
echo $sql;
exit;