[英]Using a variable value as a where statement inside PDO query
可以说我有以下变量:
$where = "where `hats`='red'";
我想将此变量注入PDO语句。 这样做的正确方法是什么?
是这样吗?:
$sql = "select * from `clothing` :where";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':where', $where);
$stm->execute();
任何帮助将不胜感激。
您只能绑定值 ,而不能绑定关键字,对象名称或语法元素。 例如,如果你总是根据hats
查询,你可以绑定'red'
值:
$color = 'red';
$sql = "select * from `clothing` where hats = :color";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':color', $color);
$stm->execute();
如果你的where
子句真的那么动态,你不得不求助于字符串操作(并且不幸地面临SQL注入的风险):
$where = "where `hats`='red'";
$sql = "select * from `clothing` $where";
$stm = $this->app->db->prepare($sql);
$stm->execute();
//在连接文件中按名称$ PDO创建一个新的PDO对象
在你的功能
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
我希望它能奏效。 它将返回数组,随意遍历它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.