在下面这个仅用作多行数据的 SELECT 语句的片段中,它在
$stmt->bind_param($types, ...$values);
上给出了错误:
mysqli_stmt::bind_param() 不接受未知命名参数
我理解一般的错误,但
$Query
是动态的,其中已经有必要的问号,但可能有任意数量的 $types
和 $values
或者可能只有一个。
$results_array = [];
if (!empty($values)) :
$stmt = $mysqli->prepare($Query);
$stmt->bind_param($types, ...$values);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array()) :
$results_array[] = $row;
endwhile;
$stmt->close();
return $results_array;
endif;
$mysqli
当然包含连接字符串,而 $Query
是正在使用的动态查询,它已经包含问号,而 $types
包含相关的字段类型,即“sssi”或其他任何内容,并与 $values
中的数据匹配
数组。
我在 7.4 中开始将准备好的语句转换为我的网站,因此任何关于 8.1 代码的建议,如果不同,都会很棒。
多亏了下面的帮助,它现在似乎可以正常工作了。由于其中一些来自答案和评论,我不能相信,我将把它附加到问题中,因为当前的问题似乎已经解决了!我也详细说明了一点。这是更大功能的一小部分。
// For queries with parameters, use prepared statement
$results_array = [];
if (!empty($values) && str_contains($Query, '?')) :
$stmt = $mysqli->prepare($Query);
$stmt->bind_param($types, ...$values);
$stmt->execute(array_values($values));
$result = $stmt->get_result();
if ($selType === "assoc") :
while($row = $result->fetch_assoc()) :
$results_array[] = $row;
endwhile;
else :
while($row = $result->fetch_array()) :
$results_array[] = $row;
endwhile;
endif;
$stmt->close();
return $stmt->get_result()->fetch_all();
// For queries without parameters, use mysqli
else :
if ($result = $mysqli->query($Query)) :
$numrowsCat = $result->num_rows;
if ($numrowsCat >= 1) :
if ($selType === "assoc") :
while($row = $result->fetch_assoc()) :
$results_array[] = $row;
endwhile;
else :
while($row = $result->fetch_array()) :
$results_array[] = $row;
endwhile;
endif;
return $results_array;
endif;
endif;
endif;
可以根据值的个数动态生成SQL查询的问号,然后用
mysqli_stmt::bind_param()
将值绑定到参数上
重构代码后,它应该看起来像这样。
$results_array = [];
if (!empty($values)) {
$num_values = count($values);
$question_marks = str_repeat("?,", $num_values);
$question_marks = rtrim($question_marks, ",");
$Query .= " VALUES (" . $question_marks . ")";
$stmt = $mysqli->prepare($Query);
$stmt->bind_param($types, ...$values);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array()) {
$results_array[] = $row;
}
$stmt->close();
}
return $results_array;
您似乎正在尝试解压缩关联数组。它需要是一个列表。您可以只使用
array_values
将其转换为列表。
您的代码在 PHP 8.1 上简化后应如下所示:
$results_array = [];
if (!empty($values)) :
$stmt = $mysqli->prepare($Query);
$stmt->execute(array_values($values));
return $stmt->get_result()->fetch_all();
endif;