首页 > 解决方案 > 准备好的选择语句的结果作为数组

问题描述

我想将准备好的语句的完整结果作为数组(键/值对)获取,以便以后在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

标签: phpsqlarraysmysqliprepared-statement

解决方案


确实有更简单的方法。请考虑使用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函数的答案


推荐阅读