我写了这个简单的代码从sql表中删除博客.但它给了一个错误
Could not delete data: Unknown column '$qid' in 'where clause'
不能理解为什么. $qid是变量,而qid是列名,它给了我这个错误.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('trial1');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
function check_login(){
return 12;
}
$return_array = array();
if( check_login()!=NULL){
$qid =1;
$sql='DELETE FROM blog_post WHERE qid = $qid';
$retval = mysql_query($sql, $conn);
if (!$retval){
die('Could not delete data: ' . mysql_error());
$return_array["success"] = 0; //If deletion unsuccessful
echo json_encode($return_array);
}
else{
$return_array["success"]=1; //If deletion successful
echo json_encode($return_array);
}
}
?>
解决方法:
变量不会用单引号引起来.将SQL查询用双引号“引起来.
$sql="DELETE FROM `blog_post` WHERE `qid` = $qid"; //<-- Like this.
从PHP 5.5.0开始不推荐使用(mysql_ *)扩展名,以后将删除.相反,应使用扩展名MySQLi
或PDO_MySQL
的预处理语句来抵御SQL注入攻击!