Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

php - Is it possible to use mysqli_fetch_object with a prepared statement

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 code snippet, as fetch_object returns null.

$sql = "select 1 from dual";
printf("preparing %s
", $sql);
$stmt = $link->prepare($sql);
printf("prepare statement %s
", is_null($stmt) ? "is null" : "created");
$rc = $stmt->execute();
printf("num rows is %d
", $stmt->num_rows);
$result = $stmt->result_metadata();
printf("result_metadata %s
", is_null($result) ? "is null" : "exists");
$rc = $result->fetch_object();
printf("fetch object returns %s
", is_null($rc) ? "NULL" : $rc);
$stmt->close();

The output is:

preparing select 1 from dual
prepare statement created
num rows is 0
result_metadata exists
fetch object returns NULL
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...