如何将 php 变量放入查询中?
$shopid = $pdo->query('SELECT shopid FROM `shop` WHERE shopname='$shopname'')->fetchAll(PDO::FETCH_ASSOC);
这不起作用,错误消息显示:“解析错误:语法错误,意外'$shopname'(T_VARIABLE)”
不
不要以这种方式插入参数。你应该使用bindParam
$statement = $db->prepare('SELECT shopid FROM shop WHERE shopname=:shopname');
$statement->bindParam(':shopname', $shopname, PDO::PARAM_STR);
$statement->execute();
如果$shopname
来自不受信任的来源,那么您很容易接受 SQL 注入。要解决此问题,您应该使用 PDO 及其准备好的语句 API:
$query = $pdo->prepare("SELECT shopid FROM shop WHERE shopname = ?");
$query->bindValue(1, $shopname, PDO::PARAM_STR);
$query->execute();
$shopid = $query->fetchAll(PDO::FETCH_ASSOC);
您没有正确包装查询。
$shopid = $pdo->query("SELECT shopid FROM `shop` WHERE `shopname`='$shopname'");
如果你支持 PDO,为什么不使用 prepare,它更安全。
$stmt = $pdo->prepare('SELECT shopid FROM shop WHERE shopname=:shopname');
$stmt->bindParam(':shopname', $shopname);
$shopname = $yourdefined;
$stmt->execute();
$stmt->bindColumn(1, $shopid);
while($stmt->fetch()){
echo $shopid,PHP_EOL;
}
好吧,您也可以像这样使用基本 sql:
$shopid = $pdo->query('SELECT shopid FROM `shop` WHERE shopname=\'{$shopname}\'')->fetchAll(PDO::FETCH_ASSOC);
尝试这个:
$query = "SELECT shopid FROM shop WHERE shopname= '".$shopname."'";
$result = mysql_query($query);