Is it possible to use mysqli_fetch_object with a prepared statement

前端 未结 3 1451
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 15:22

All the examples I see using mysqli_fetch_object use mysql_query(), I cannot get it to work with prepared statements. Does anyone know what is wrong with this c

3条回答
  •  遥遥无期
    2020-12-03 16:07

    This is the code I use to create an object from a prepared statement.
    It could perhaps be used in a subclass of mysqli?

        $query = "SELECT * FROM category WHERE id = ?";
        $stmt = $this->_db->prepare($query);
    
        $value = 1;
        $stmt->bind_param("i", $value);
    
        $stmt->execute();
    
        // bind results to named array
        $meta = $stmt->result_metadata();
        $fields = $meta->fetch_fields();
        foreach($fields as $field) {
            $result[$field->name] = "";
            $resultArray[$field->name] = &$result[$field->name];
        }
    
        call_user_func_array(array($stmt, 'bind_result'), $resultArray);
    
        // create object of results and array of objects
        while($stmt->fetch()) {
            $resultObject = new stdClass();
    
            foreach ($resultArray as $key => $value) {
                $resultObject->$key = $value;
            }
    
            $rows[] = $resultObject;
        }
    
        $stmt->close();
    

提交回复
热议问题