dsjws44266 2018-07-13 12:09
浏览 69
已采纳

准备的select语句作为数组的结果

I would like to get the complete result of a prepared statement as an array (key/value pairs) in order to later use it in a str_replace() function.

My table has three columns, an index and the fields "x1" and "x2". I used the following successfully:

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

However, I am thinking that there must be a simpler way, without a while loop, getting the complete result, not added up from single rows one by one.

I looked at other questions, and I came up with the following, but it doesn't work ("Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result"):

if($ps1 = $db->prepare("SELECT x1, x2 FROM my_table")) {
  $ps1->execute();
  $result = mysqli_fetch_assoc($ps1);
  return $result;
  $ps1->close();
}

I also tried $result = mysqli_fetch_all($ps1); with no success ( getting "Call to undefined function mysqli_fetch_all()").

BTW, I am using PHP 5.6.


ADDITION after some answers and discussion in comments concerning MYSQLND:

phpinfo() displays the following information in its mysqlnd section:

Loaded plugins: mysqlnd,debug_trace,auth_plugin_mysql_native_password,auth_plugin_mysql_clear_password,auth_plugin_sha256_password

  • 写回答

7条回答 默认 最新

  • duanji8887 2018-07-17 15:03
    关注

    Did you try something like this ?

    $db = new mysqli("servername", "username", "pw", "dbname");
    
    if($ps1 = $db->prepare("SELECT x1, x2 FROM my_table")) {
      $ps1->execute();
      $result = $ps1->fetchAll(PDO::FETCH_NAMED);
      $ps1->close();
    }
    

    UPDATE

    I mean like this (in case you have installed the mysqlnd driver)

    <?php
    $link = mysqli_connect("localhost", "my_user", "my_password", "world");
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
    ", mysqli_connect_error());
        exit();
    }
    
    $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
    
    if ($stmt = mysqli_prepare($link, $query)) {
    
        /* execute statement */
        mysqli_stmt_execute($stmt);
    
        /* get result object */
        $result = mysqli_fetch_all(mysqli_stmt_get_result($stmt));
    
        /* close statement */
        mysqli_stmt_close($stmt);
    }
    
    /* close connection */
    mysqli_close($link);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集