我想将准备好的语句的完整结果作为数组(键/值对)获取,以便稍后在 str_replace()
函数中使用它。
我的表有三列,一个索引和字段“x1”和“x2”。我成功地使用了以下内容:
$db = new mysqli("servername", "username", "pw", "dbname");
if($ps1 = $db->prepare("SELECT x1, x2 FROM my_table")) {
$ps1->execute();
$ps1->bind_result($search, $replace);
$result = array();
while ($ps1->fetch()) {
$result[$search] = $replace;
}
$ps1->close();
}
不过,我在想一定有更简单的方法,不用while
循环,得到完整的结果,而不是从单行开始逐行累加。
我查看了其他问题,并得出了以下结论,但它不起作用(“警告:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result”):
if($ps1 = $db->prepare("SELECT x1, x2 FROM my_table")) {
$ps1->execute();
$result = mysqli_fetch_assoc($ps1);
return $result;
$ps1->close();
}
我也试过 $result = mysqli_fetch_all($ps1);
但没有成功(得到“调用未定义的函数 mysqli_fetch_all()”)。
顺便说一句,我使用的是 PHP 5.6。
在有关 MYSQLND 的评论中进行一些回答和讨论后添加:
phpinfo()
在其 mysqlnd
部分显示以下信息:
Loaded plugins: mysqlnd,debug_trace,auth_plugin_mysql_native_password,auth_plugin_mysql_clear_password,auth_plugin_sha256_password
最佳答案
确实有更简单的方法。请考虑使用 array_column :
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT x1, x2 FROM my_table";
if ($stmt = mysqli_prepare($link, $query)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* get result object */
$rows = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
/* get formatted object */
$result = array_column($rows, 'x2', 'x1');
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
编辑:更新了使用过程mysqli 函数的答案
关于php - 准备好的 select 语句的结果作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51324788/