Sometimes there are queries that bring several columns and it is tedious to have to bind the result of each column to a variable. In those cases one might prefer to store the result set in an array using for example the fetch_assoc
.
With a query obtained using query
, (unprepared queries), there is no problem. But when it comes to prepared queries mysqli
it makes things really difficult and I don't understand why.
Investigating, I thought I found the solution... The PHP Manual describes the method get_result
, as the best way to obtain a set of results from a query prepared within an associative array.
But this Manual note makes your relationship with mysqli irreconcilable:
Available only with mysqlnd .
mysqlnd
it does not come installed on all systems... and this limitation is not valid when you try to give an answer to questions raised here.
The question
How to store a result set in an associative array in mysqli using prepared queries if mysqlnd is not installed?
In this code I implemented a function mi_fetchassoc
that does the job, but it's not ideal... also in it I have to specify each time how the columns are called.
function mi_fetchassoc($stmt)
{
if($stmt->num_rows>0)
{
$rs = array();
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$rs[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
if($stmt->fetch())
return $rs;
}
return null;
}
I found this answer on SO , with some interesting examples, maybe it can help you.
Example:
Here's a neater solution based on the same principle:
Normally without mysqInd you would do:
Normally with mysqInd you would do:
@A.Cedano has tested it and it works perfectly, here you can see an answer by the most complete ( How do I secure my connection from PHP to MySQL? ).
One other alternative, in case of receiving data via PHP json_decode
It is querying the elements of the array directly in
bind_result()
, instead of using separate variables.And we get desired results by means of
json_decode