我的团队和我正在尝试基于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,给定对象
经过一些search我们无法确切地告诉我们在 mysqli_stmt_bind_result 或 mysqli_fetch_assoc()
中的错误问题: 请问如何以程序方式绑定参数?
答案 0 :(得分:1)
您需要将查询更改为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);
}