gpt4 book ai didi

php - 在 php 和 mysqli 中使用准备好的语句

转载 作者:行者123 更新时间:2023-11-29 12:20:35 24 4
gpt4 key购买 nike

我是第一次使用准备好的语句。我无法让选择工作。由于某种原因,它返回所有记录,但我无法将它们放入变量中。我知道它会返回所有记录,因为如果我将 echo '1'; 添加到循环中,它会为每条记录回显 1。

任何帮助都会很棒。代码如下:

function builditems($quote_id){
if ($stmt = $this->link->prepare("SELECT * FROM `0_quotes_items` WHERE `quote_id` = ?")) {
// Bind a variable to the parameter as a string.
$stmt->bind_param("i", $quote_id);
// Execute the statement.
$stmt->execute();
while ($row = $stmt->fetch()) {
echo $row['id'];
}


// Close the prepared statement.
$stmt->close();
}
}

更新:在错误日志中,按照建议添加 while ($row = $stmt->fetch_assoc()) { 后,我看到以下错误:

PHP fatal error :调用未定义的方法 mysqli_stmt::fetch_assoc()

我发现一个链接存在同样的问题,但我不明白如何实现修复。任何关于示例的帮助都会很棒。

How to remove the fatal error when fetching an assoc array

最佳答案

PHP MySQLi fetch 方法不使用括号表示法访问查询数据:$row['id']

所以我看到两个选项可以补救:首先找到这一行:

while ($row = $stmt->fetch()) {

...并将其修改为,任一,首先添加 bind_result 方法,然后以稍微不同的方式访问数据:

$stmt->bind_result($id, $other, $whatnot); // assuming 3 columns retrieved in the query
while ($row = $stmt->fetch()) {
echo "$id $other $whatnot<br>";
}

...,首先访问 result 对象的 fetch_assoc 方法,并使用 fetch_assoc 而不是 获取:

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {

现在您可以使用表列名称作为键来访问循环中的查询数据:$row['id']

<小时/>

PHP MySQLi 方法 fetch要求您使用bind_result。这样做可以让您通过绑定(bind)到的变量名称来调用数据。

要使用字段名作为结果数组索引,如:$row['id'],需要使用 PHP MySQLi fetch_assoc方法。要使用 fetch_assoc,您需要首先获取 result 对象,以便访问 fetch_assoc 方法。

关于php - 在 php 和 mysqli 中使用准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29087516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com