如何在 php 中使用 bind_result() 而不是 get_result()
我正在为 uni 开发一个项目,并且一直在 testing server 上使用以下代码从基于 的表中:获取所有设备user_id
I'm working on a project for uni and have been using the following code on a testing server to get all devices from a table based on a user_id:
public function getAllDevices($user_id) {
$stmt = $this->conn->prepare("SELECT * FROM devices WHERE primary_owner_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$devices = $stmt->get_result();
$stmt->close();
return $devices;
}
这在我的测试服务器上运行良好,但在迁移到大学项目服务器时返回此错误:
This worked fine on my testing server but returns this error when migrating over to the university project server:
Call to undefined method mysqli_stmt::get_result()
一些谷歌搜索建议使用 bind_result() 而不是 get_result() 但我不知道如何在表中执行此all fields.大多数示例只显示返回 one field
Some googling suggests using bind_result() instead of get_result() but I have no idea how to do this all fields in the table. Most examples only show returning one field
任何帮助将不胜感激
推荐答案
假设你不能使用 get_result() 并且你想要一个设备数组,你可以这样做:
Assuming you can't use get_result() and you want an array of devices, you could do:
public function getAllDevices($user_id) {
$stmt = $this->conn->prepare("SELECT device_id, device_name, device_info FROM devices WHERE primary_owner_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($id, $name, $info);
$devices = array();
while($stmt->fetch()) {
$tmp = array();
$tmp["id"] = $id;
$tmp["name"] = $name;
$tmp["info"] = $info;
array_push($devices, $tmp);
}
$stmt->close();
return $devices;
}
这会创建一个临时数组并存储其中每一行的数据,然后将其推送到主数组.据我所知,您不能在 bind_result() 中使用 SELECT *.相反,您将不得不在 SELECT
This creates a temporary array and stores the data from each row in it, and then pushes it to the main array. As far as I'm aware, you can't use SELECT * in bind_result(). Instead, you will annoyingly have to type out all the fields you want after SELECT
相关文章