php - 准备好的选择语句的结果作为数组
问题描述
我想将准备好的语句的完整结果作为数组(键/值对)获取,以便以后在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
在其部分中显示以下信息:
加载的插件: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函数的答案
推荐阅读
- r - 试图用具有 NA 值的数据框计算行的总和
- python - 散点图根据值标记不同的颜色
- android-studio - 我可以从我的 Google Play 商店中完全删除我的应用吗?
- amazon-web-services - 如何从 lambda 函数中触发警报
- java - 如何确定 apk 是否用 Java 签名?
- php - 帖子不存在
- python-3.x - 在 Report Lab 中创建 4 x 5 的图像网格 - Python
- javascript - 如何修复此功能?Javascript
- swift - 如何确保在返回值之前获得 Firebase getDocument 结果?
- html - 我想在数据错误列旁边突出显示数据?我应该怎么办?