note 117275 added to mysqli-stmt.fetch
| From: | Brian | Date: | Thu, 14 May 2015 18:09:55 +0000 |
| Subject: | note 117275 added to mysqli-stmt.fetch | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202519@lists.php.net to get a copy of this message | ||
Same as everyone else, I was looking for a way NOT to have to duplicate the amount of code it takes
to fetch the results of a prepared statement as an associative array.
Some of the other methods didn't work as written, and this one is packaged into a simple
function to reduce code repetition.
Adapted from code others have posted.
<?php
// Example usage:
$id = 1;
$stmt = $dbc->prepare("SELECT * FROM table WHERE id=?");
if (!$stmt->bind_param('i', $id) || !$stmt->execute()) {
throw new \Exception("Database error: $stmt->errno - $stmt->error");
}
$results = fetch_assoc_stmt($stmt);
$stmt->close();
/**
* Fetches the results of a prepared statement as an array of associative
* arrays such that each stored array is keyed by the result's column names.
* @param stmt Must have been successfully prepared and executed prior to calling this function
* @param buffer Whether to buffer the result set; if true, results are freed at end of function
* @return An array, possibly empty, containing one associative array per result row
*/
function fetch_assoc_stmt(\mysqli_stmt $stmt, $buffer = true) {
if ($buffer) {
$stmt->store_result();
}
$fields = $stmt->result_metadata()->fetch_fields();
$args = array();
foreach($fields AS $field) {
$key = str_replace(' ', '_', $field->name); // space may be valid SQL, but
not PHP
$args[$key] = &$field->name; // this way the array key is also preserved
}
call_user_func_array(array($stmt, "bind_result"), $args);
$results = array();
while($stmt->fetch()) {
$results[] = array_map("copy_value", $args);
}
if ($buffer) {
$stmt->free_result();
}
return $results;
}
/**
* Copy value as value
*/
function copy_value($v) {
return $v;
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 76.121.92.234
----
Manual Page -- http://php.net/manual/en/mysqli-stmt.fetch.php
Edit -- https://master.php.net/note/edit/117275
Del: integrated -- https://master.php.net/note/delete/117275/integrated
Del: useless -- https://master.php.net/note/delete/117275/useless
Del: bad code -- https://master.php.net/note/delete/117275/bad+code
Del: spam -- https://master.php.net/note/delete/117275/spam
Del: non-english -- https://master.php.net/note/delete/117275/non-english
Del: in docs -- https://master.php.net/note/delete/117275/in+docs
Del: other reasons-- https://master.php.net/note/delete/117275
Reject -- https://master.php.net/note/reject/117275
Search -- https://master.php.net/manage/user-notes.php