如何以过程化的方式绑定参数


How to bind parameters in a procedural way

我和我的团队正试图根据php中对PDO所做的操作,以程序化的方式绑定参数,但当我们这样做时,我们得到了以下错误:

警告:mysqli_fetch_assoc()要求参数1为给定对象的mysqli_result

我们想要转化为过程性的原始PDO工作代码是:

    $last_id = $_POST['last_id'];
$limit = 5; // default value
if (isset($_POST['limit'])) {
    $limit = intval($_POST['limit']);
}
try {
        $sql = 'SELECT * FROM items WHERE id > :last_id ORDER BY id ASC LIMIT 0, :limit';
        $query = $pdo->prepare($sql);
        $query->bindParam(':last_id', $last_id, PDO::PARAM_INT);
        $query->bindParam(':limit', $limit, PDO::PARAM_INT);
        $query->execute();
        $list = $query->fetchAll();
    } catch (PDOException $e) {
        echo 'PDOException : '.  $e->getMessage();
    }

以下是我们将其转化为程序的方法:

$last_id = $_POST['last_id'];
$limit = 5; // default value
if (isset($_POST['limit'])) {
    $limit = intval($_POST['limit']);
}

 $stmt = mysqli_prepare($connection, "SELECT id, photo, title, description FROM items WHERE id > ?  ORDER BY id ASC LIMIT 0, ?") or die(mysqli_error($connection));
    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, 'ii', $last_id, $limit) or die(mysqli_error($connection));

    /* execute query */
    mysqli_stmt_execute($stmt) or die(mysqli_error($connection));
    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $col1, $col2,$col3, $col4) or die(mysqli_error($connection));
########################################


$last_id = 0;

while( $rs = mysqli_fetch_assoc($stmt)) 
{
    $last_id = $rs['id'];
    echo '<li>';
    echo '<h2>'.$rs['title'].'</h2>';
    echo '<img src="'.$rs['photo'].'">';
    echo '<p>'.$rs['description'].'</p>';
    echo '</li>';
}

if ($last_id != 0) {
    echo '<script type="text/javascript">var last_id = '.$last_id.';</script>';
}

问题使用我们的程序方法,我们不断收到以下错误消息:

警告:mysqli_fetch_assoc()要求参数1为给定对象的mysqli_result

经过一番搜索后,我们无法真正判断我们在mysqli_stmt_bind_resultmysqli_fetch_assoc()中的错误位置

问题:请说明如何以过程方式绑定参数?

根据本文档mysqli_stmt_bind_result

您需要将查询更改为SELECT col1,col2.....,而不是select *

mysqli_stmt_bind_param($stmt, 'ii', $last_id, $limit) or die(mysqli_error($connection));// here use int because `$last_id, $limit` are integer
    /* execute query */
    mysqli_stmt_execute($stmt) or die(mysqli_error($connection));
    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $col1, $col2,$col3, $col4) or die(mysqli_error($connection));

使用获取数据

 /* fetch values */
 while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s'n", $col1, $col2);
    }