How can I put the results of a MySQLi prepared statement into an associative array?
Try the following:
$meta = $statement->result_metadata();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($statement, 'bind_result'), $params);
while ($statement->fetch()) {
foreach($row as $key => $val) {
$c[$key] = $val;
}
$hits[] = $c;
}
$statement->close();
First you get the query metadata and from that obtain all the fields you've fetched (you could do this manually, but this code works for all queries rather than building by hand). The call_user_func_array()
function calls the mysqli_stmt::bind_result()
function for you on each of those parameters.
After that it is just a matter of running through each row and creating an associative array for each row and adding that to an array resulting in all the results.
PHP mysqli - return an associative array from a prepared statement
If you have the MySql Native Driver extension (mysqlnd), you can use the get_result method to obtain a ResultSet, and then fetch from it the usual way:
$query = $c->prepare("SELECT e._id,e.description,e.eventDate,e.eventTime,e.address,e.locationDescription,i.guestId,r.guestId IS NOT NULL AS 'RSVP-ed' FROM eventList AS e JOIN inviteList AS i ON e._id = i.eventId LEFT JOIN rsvpList AS r ON r.eventId = e._id AND i.guestId = r.guestId JOIN guestList AS g ON g._id = i.guestId WHERE g.groupName = ?");
$query->bind_param('s',$groupName);
$query->execute();
$result = $query->get_result();
$a = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
Get ASSOC array with PDO without using prepared statement
the statement needs to be executed ...
$stmt = $db->query("SELECT * from tracks WHERE online = 1");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
passing it as second argument should also work:
$stmt = $db->query("SELECT * from tracks WHERE online = 1", PDO::FETCH_ASSOC);
$data = $stmt->fetchAll();
or as one-liner:
$data = $db->query("SELECT * from tracks WHERE online = 1")->fetchAll(PDO::FETCH_ASSOC);
there's also:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
Related Topics
How to Count Days Between Two Dates in PHP
Jquery Mobile: How to Correctly Submit Form Data
PHP HTML Domdocument Getelementbyid Problems
How to Detect an Incoming Request (With PHP Script) from a Cname Subdomain
PHP Curl Curlopt_Ssl_Verifypeer Ignored
What Does Filter_Sanitize_String Do
PHP Curl: I Need a Simple Post Request and Retrival of Page Example
Using Array_Search for Multi Dimensional Array
How to Find the Date of a Day of the Week from a Date Using PHP
How to Call a PHP Script/Function on a HTML Button Click
Hide Shipping Methods for Specific Shipping Class in Woocommerce
Passing PHP Variable from Controller to JavaScript Function in the Head of a View