Php 在PDO查询中使用变量值作为where语句
假设我有以下变量:Php 在PDO查询中使用变量值作为where语句,php,mysql,pdo,Php,Mysql,Pdo,假设我有以下变量: $where = "where `hats`='red'"; 我想把这个变量注入到PDO语句中。这样做的正确方式是什么 是这样吗 $sql = "select * from `clothing` :where"; $stm = $this->app->db->prepare($sql); $stm->bindParam(':where', $where); $stm->execute(); 任何帮助都将不胜感激。您只能绑定值,不能绑定关键字、
$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注入的风险):
只能绑定值,不能绑定关键字、对象名称或语法元素。例如,如果您总是根据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注入的风险):
//在连接文件中创建名为$PDO的新PDO对象 在你的职责范围内
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
我希望它能起作用。它将返回数组,随意遍历它//在连接文件中创建一个名为$PDO的新PDO对象 在你的职责范围内
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
我希望它能起作用。它将返回数组,根据需要遍历它我向上投票以使您平衡。我同意,我正在构建一个动态where语句,我想我唯一的选择是直接注入它。我投票支持你。我同意,我正在构建一个动态where语句,我想我唯一的选择是直接注入它。