0 down vote favorite
I'm trying to retrieve the results of a query using mysqli and put them into an associative array. After searching online I found this post:
http://stackoverflow.com/questions/994041/how-can-i-put-the-results-of-a-mysqli-prepared-statement-into-an-associative-arr
Where this code is outlined:
$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();
I've been trying to implement the technique but something isn't working and I don't know if it's because I'm understanding it wrong or not.
So this is, line by line, what I think is going on (please correct me if I'm wrong):
$meta = $statement->result_metadata();
Set the variable "$meta" a result object containing the metadata from the query I prepared
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
Loop through the array of objects representing the fields in the meta data (returned from the fetch_field method) and for each of them set the key of a new array "$params" to the field's "name" property
call_user_func_array(array($statement, 'bind_result'), $params);
Use the "call_user_fun_array" function to call the method "bind_result" from the object "$statement" and pass into it our "$params" array, meaning that we would be setting up each of the keys in the "$param" array to catch the results of our query when it runs
while ($statement->fetch()) {
Start fetching the prepared query
foreach($row as $key => $val) {
For each row of the returned array, assign the key to the variable "$key"
$c[$key] = $val;
And then create a new associative array "$c" where the key is set to the value of "$key" and it's value is the current element's value
$hits[] = $c;
And then take the array "$c" assign it to another new array "$hits"
Blergh, sorry if it gets a bit muddied towards the end. I think it reflects my confusion over the situation. I guess I follow the logic all of the way up until the while loop where we're looping through the results of our query. Could someone straighten this out logically for me?
Kishor Makwana
Software Engineer
Insight Softech
www.insightsoftech.com