我以为我想要的很简单,但由于某种原因,我被卡住了。我有以下内容:
$sql = "...";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("sss", $x,$y,$z);
if ($stmt->execute()) {
$result = array(); //not sure if needed
$stmt->bind_result($x1,$y1,$z1); //not sure if needed
//loop resultset and put it in an array ($result);
echo json_encode($result); // convert to json
$stmt->close();
}
}
我看到了fetchAll、fetch_assoc等等,但这些调用/函数的错误一直是未定义的。其他例子是未经准备的发言。无论我尝试了什么,都没能用结果集创建数组,我缺少什么?
感谢
使用bind_result
后,您仍然需要获取这些:
$sql = "SELECT col1, col2, col3 FROM table_name WHERE col4 = ? AND col5 = ? AND col6 = ?";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param('sss', $x,$y,$z);
if ($stmt->execute()) {
$result = array();
$stmt->bind_result($x1,$y1,$z1);
// You forgot this part
while($stmt->fetch()) {
$result[] = array('col1' => $x1, 'col2' => $y1, 'col3' => $z1);
}
echo json_encode($result); // convert to json
$stmt->close();
}
}
或者,如果系统上有mysqlnd
驱动程序:
$sql = "SELECT col1, col2, col3 FROM table_name WHERE col4 = ? AND col5 = ? AND col6 = ?";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param('sss', $x,$y,$z);
if ($stmt->execute()) {
$data = $stmt->get_result();
$result = array();
while($row = $data->fetch_assoc()) {
$result[] = $row;
}
echo json_encode($result); // convert to json
$stmt->close();
}
}