【问题标题】:PDO parameterized query not returning anythingPDO 参数化查询不返回任何内容
【发布时间】:2013-12-24 02:04:10
【问题描述】:

我正在将旧的 mysql_query 代码转换为 PDO 参数化查询。这是我到目前为止所拥有的。它似乎没有返回任何东西。我在 phpmyadmin 中尝试了相同的查询,并且在旧代码中使用相同的输入,查询以这些方式返回行。

public function searchArticle($input)
{
 $db = new PDO("mysql:host=localhost;dbname=thecorrectdbname", "root", "supersecretpassword");    

    $statement = $db->prepare("SELECT * FROM news WHERE headline LIKE '%:title%'
                            OR content LIKE %:content%'
                            OR author LIKE '%:author%'
                            ORDER BY id DESC");

    $statement->execute(array('title' =>$query, 
                            'content' =>$query,
                            'author'=>$query));

    $result = $statement->fetchAll();

    print_r($result);

    if (!$result || $statement->rowCount() <= 0)
    {
        echo'nothing in this array';
        return false;
    }

    return $result;
 }

返回

 Array ( ) nothing in this array 

使用相同的 $db 连接,我可以设法将数据插入数据库,因此连接正常。

两个问题。

  1. 我在这段代码中做错了什么?

  2. 假设我能让代码正常工作。 PDO 准备语句返回的 $result 对象在结构上是否与 mysql_query $result 对象相同?如果没有,我如何将 PDO 结果集转换为 mysql_query ?

【问题讨论】:

  • $query 似乎没有任何价值。此外, %:content%' 缺少一个 '.而且我不认为它是这样工作的:你必须使用 concat('%', :content, '%') (或者见尼克的回答)
  • ^ 并且由于它们是绑定参数,因此键应以冒号为前缀:':title' =&gt; $someTitle, ':content' =&gt; $someContent, ':author' =&gt; $someAuthor

标签: php mysql pdo parameterized-query


【解决方案1】:

您的替换变量将被 PDO 自动转义和引用,这意味着您不能在引号内包含变量。

更改以下内容:

$statement = $db->prepare("SELECT * FROM news WHERE headline LIKE :title
                            OR content LIKE :content
                            OR author LIKE :author
                            ORDER BY id DESC");

$statement->execute(array('title' =>'%'.$query.'%', 
                            'content' =>'%'.$query.'%',
                            'author'=>'%'.$query.'%'));

【讨论】:

  • 这行得通,谢谢!下一次,我应该马上去 StackOverflow,而不是尝试 2 小时。 :D
【解决方案2】:

您对占位符的使用无效。必须使用占位符代替整数值。

$statement = $db->prepare("SELECT * FROM news WHERE headline LIKE :title
                        OR content LIKE :content
                        OR author LIKE :author
                        ORDER BY id DESC");

$statement->execute(array('title' =>"%$query%", 
                        'content' =>"%$query%",
                        'author'=>"%$query%"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    相关资源
    最近更新 更多