如何将MySQLi准备语句的结果放入关联数组中? [英] How can I put the results of a MySQLi prepared statement into an associative array?

查看:64
本文介绍了如何将MySQLi准备语句的结果放入关联数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个sql查询和一个mysqli准备好的语句:

I have a sql query and a mysqli prepared statement:

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

$stmt = $conn->stmt_init(); 
if ($stmt->prepare($sql)) { 
    $stmt->bind_result($photographer_id, $photographer_name);  
    $OK = $stmt->execute(); 
    $stmt->fetch();
}

如何将结果存储在关联数组中,以便以后可以循环并获取sql字符串返回的所有数据?

How can I store the results in an associative array so I can loop it later and get to all the data returned by the sql string?

推荐答案

尝试以下操作:

$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(); 

首先,您获得查询元数据,并从中获取所有已获取的字段(您可以手动执行此操作,但是此代码适用于所有查询,而不是手动构建). call_user_func_array() 函数调用 mysqli_stmt::bind_result() 为您提供这些参数中的每个功能.

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.

这篇关于如何将MySQLi准备语句的结果放入关联数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆