替换“?”与数组数据

时间:2017-04-10 13:48:28

标签: php pdo bdd

我正在使用使用PDO进行请求的软件。数据库请求是这样的:

$query = "SELECT * FROM res_attachments WHERE res_id = ? AND status = ?";
$data = array('152', 'DEL');

我的问题是,如何用“?”获得整个请求?用$ data元素替换?我在查询后得到这个信息($ query和$ data),我只需要“合并”它。我必须制作一个动态的东西,使用2 arg或10 args的请求。

我想要的结果必须是:

"SELECT * FROM res_attachments WHERE res_id = '152' AND status = 'DEL'"

解决方案

对于那些有类似问题的人,我提出了以下解决方案:

$query = "SELECT * FROM res_attachments WHERE res_id = ? AND status = ?";
$data = array('152', 'DEL');
$tab = explode("?",$query);
for($i =0; $i < count($tab); $i++){
    $Request .= $tab[$i] . "'" . $data[$i] . "'";
    $finalRequest = str_replace('\'\'', '', $Request); // delete the double quote at the end
}
var_dump($finalRequest);

4 个答案:

答案 0 :(得分:3)

您要找的是prepare()然后执行而不是query()

query()运行标准SQL语句,要求您正确转义所有数据以避免SQL注入和其他问题。

这就是你想要的:

<?php

$query = "SELECT * FROM res_attachments WHERE res_id = ? AND status = ?";
$data = array($res_id, $status);
$stmt = $db->prepare($query);
if($stmt->execute($data)){
    //fetch your results

}
?>

或:

<?php

$query = "SELECT * FROM res_attachments WHERE res_id = :id AND status = :status";
$stmt  = $db->prepare($query);
if ($stmt->execute(array(
    ':id' => $res_id,
    ':status' => $status
))) {
    //fetch results
}

?>

更新:

  

我想要的结果必须是:

    SELECT * FROM res_attachments WHERE res_id = '152' AND status = 'DEL'

然后,您可以简单地使用debugDumpParams()将预准备语句包含的信息直接转储到输出中。它将提供正在使用的SQL查询,使用的参数数量(参数),

<?php

$query = "SELECT * FROM res_attachments WHERE res_id = ? AND status = ?";
$data = array($res_id, $status);
$stmt = $db->prepare($query);
if($stmt->execute($data)){
   $stmt->debugDumpParams();
}
?>

答案 1 :(得分:1)

如果你的代码片段中的$ db是PDO的一个实例,那么你可以使用debugDumpParams()来查看SQL

答案 2 :(得分:1)

我希望这会对你有所帮助,试试这个

 $sth = $db->prepare('SELECT * FROM res_attachments WHERE res_id = ? AND status = ?');
    $sth->bindParam(1, $res_id, PDO::PARAM_INT);
    $sth->bindParam(2, $status, PDO::PARAM_STR);
    $sth->execute();

OR

$q = $db -> prepare('SELECT * FROM res_attachments WHERE res_id = ? AND status = ?');
$q->execute(array($res_id,$status));

答案 3 :(得分:1)

试试这个,我使用preg_replace_callback的方法:

$index = -1;
echo preg_replace_callback(
    '/\?/',
    function () use ($data, &$index) {
        $index++;
        return "'{$data[$index]}'";
    },
    $query);