如何在SQL查询中插入PHP变量?我的查询有误吗?

我写了这个简单的代码从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_ *)扩展名,以后将删除.相反,应使用扩展名MySQLiPDO_MySQL的预处理语句来抵御SQL注入攻击!

上一篇:在python中解压缩对象变量


下一篇:linux-导出在shell中是变量值的变量