How can I put the results of a MySQLi prepared statement into an associative array?

后端 未结 7 1498
清酒与你
清酒与你 2020-12-01 09:54

I have a sql query and a mysqli prepared statement:

$sql = \'SELECT photographers.photographer_id, photographers.photographer_name
    FROM photographers\';
         


        
7条回答
  •  感情败类
    2020-12-01 10:23

    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.

提交回复
热议问题