【问题标题】:PDO bindParam not allowing statement to return resultsPDO bindParam 不允许语句返回结果
【发布时间】:2013-03-29 00:14:24
【问题描述】:

我有一个 pdo 语句来选择行并将它们返回到一个数组中。我正在使用分页显示每页 12 个结果。如果我直接输入 LIMIT 12, 12 ,而不是 LIMIT ?, ? ,则该语句可以正常工作。

我对这两个变量的 bindParam 做错了什么?

两个变量都包含正确的数据。

这是我正在使用的功能:

// Retrieve active posts
function retrieve_active_posts(){
    //test the connection
    try{
        //connect to the database
        $dbh = new PDO("mysql:host=db2940.oneandone.co.uk;dbname=db348699391","xxx", "xxx");
    //if there is an error catch it here
    } catch( PDOException $e ) {
        //display the error
        echo $e->getMessage();

    }

    // Get all the posts
    $stmt = $dbh->prepare(" SELECT  p.post_id, post_year, post_desc, post_title, post_date, img_file_name, p.cat_id
                            FROM    mjbox_posts p
                            JOIN    mjbox_images i
                            ON      i.post_id = p.post_id
                                    AND i.cat_id = p.cat_id
                                    AND i.img_is_thumb = 1
                                    AND post_active = 1
                            ORDER BY post_date
                            DESC
                            LIMIT ?,?");
    $stmt->bindParam(1, $limit);
    $stmt->bindParam(2, $offset);                       
    $stmt->execute();


    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            $resultarray[] = $row;
    }

    return $resultarray;
}

非常感谢

【问题讨论】:

  • 可以添加var_dump($limit, $offset);的输出吗?
  • @hek2mgl NULL 两者都为NULL
  • @crm 检查我的答案 ;)
  • 顺便说一句,当 PDO 为您提供 fetchAll() 时,为什么要使用 fetch() 循环遍历结果集以构建数组?
  • 另外,我认为您的参数顺序错误。首先是偏移量,然后是要返回的记录数(除非其中包含 OFFSET 关键字,在这种情况下顺序颠倒)。

标签: php mysql select binding pdo


【解决方案1】:

确保$limit$offset的类型设置为PDO::PARAM_INT

$limit = 20;
$offset = 0;

$stmt->bindParam(1, $limit,  PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);

【讨论】:

  • 我完全按照你写的那样尝试了你的例子,我收到了这个错误Fatal error: Cannot pass parameter 2 by reference
  • 真的吗? (不敢相信)。使用变量尝试我的更新示例
  • 我猜这个错误是由你的代码的其他部分触发的。上面的例子应该可以工作
  • 你的权利,我忘了将变量传递给函数#facepalm 谢谢
【解决方案2】:

连接数据库后,插入以下代码行:

$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);

来源:https://www.php.net/manual/en/pdo.setattribute.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2012-05-03
    • 2013-02-25
    相关资源
    最近更新 更多