How to use bind_result() instead of get_result() in php

前端 未结 5 1499
攒了一身酷
攒了一身酷 2020-12-18 08:57

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_

5条回答
  •  离开以前
    2020-12-18 09:33

    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;
    }
    

    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

提交回复
热议问题