PDO准备语句 - 2种类似方法中的不同行为

时间:2015-10-20 20:46:49

标签: php pdo prepared-statement

我希望有人解释为什么第一种方法仅在引用':cat_id'子句中的占位符WHERE后才能工作,并且需要$this->db->query($query);,否则会引发致命错误:< / p>

  

“SQLSTATE [HY093]:参数号无效:绑定变量数   与...中的令牌数量不匹配“

而第二种方法既不需要引用也不需要$this->db->query()方法?

public function getAllPosts($cat_id = null)
{   
    // Query build
    $query = "SELECT posts.*, users.username, categories.title FROM posts "
            . "INNER JOIN users "
            . "ON posts.user_id = users.id "
            . "INNER JOIN categories "
            . "ON posts.category_id = categories.id ";
    // Filter
    if (!is_null($cat_id))
    {
        $query .= "WHERE category_id = ':cat_id' ";

        // Order query
        $query .= "ORDER BY create_date DESC";
        $this->db->bind(':cat_id', $cat_id);
    }
    else
    {
        $query .= "ORDER BY create_date DESC";

    }
    $this->db->query($query);
    // Run the query


    // Assign Result Set
    $results = $this->db->resultset();
    return $results;
}


public function getCategoryPosts($cat_id)
{   
    $query = "SELECT posts.*, users.username, categories.title FROM posts "
            . "INNER JOIN users "
            . "ON posts.user_id = users.id "
            . "INNER JOIN categories "
            . "ON posts.category_id = categories.id "
            . "WHERE posts.category_id = :cat_id "
            . "ORDER BY create_date DESC";

    $this->db->bind(':cat_id', $cat_id);

    $results = $this->db->resultset();
    return $results;
}

更新

以下是来自第一种方法的查询的回显输出:

1。引用:

SELECT posts.*, users.username, categories.title FROM posts 
INNER JOIN users ON posts.user_id = users.id
INNER JOIN categories ON posts.category_id = categories.id 
WHERE category_id = ':cat_id' ORDER BY create_date DESC

2。无引号:

SELECT posts.*, users.username, categories.title FROM posts 
INNER JOIN users ON posts.user_id = users.id 
INNER JOIN categories ON posts.category_id = categories.id 
WHERE category_id = :cat_id ORDER BY create_date DESC

1 个答案:

答案 0 :(得分:2)

您在以下字符串中缺少尾随空格

$query .= "WHERE category_id = ':cat_id'";

所以你将它连接成:

WHERE category_id = ':cat_id'ORDER BY create_date DESC

如果您删除',则会获得:

WHERE category_id = :cat_idORDER BY create_date DESC

因此PDO期望:cat_idORDER

的绑定值

同样在getCategoryPosts()中,您创建了一个查询但从未实际使用它。