douluozhan4370 2012-09-04 22:09
浏览 41
已采纳

使用MySqli和数组返回多行

For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.

$mysqli = new mysqli("localhost", "user", "password", "database");   

function display_posts ($mysqli, $user_id) {

   $fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";   

   $user_id = (int)$user_id;

   $query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id 
   LIMIT 4";                    

   if ($result = $mysqli->query($query)) {

   $row = $result->fetch_assoc();

   return $row;

   $result->free();

   $stmt->close();

}}

Here I am trying to display the data.

$user_id = 1;

$posts = display_posts($mysqli, $user_id);

//Not sure what to do with $posts. A While loop perhaps to display each post?
  • 写回答

3条回答 默认 最新

  • douyanqu9722 2012-09-04 22:14
    关注

    You have to use a loop to get them all at once:

    <?php
    function resultToArray($result) {
        $rows = array();
        while($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        return $rows;
    }
    
    // Usage
    $query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
    $result = $mysqli->query($query);
    $rows = resultToArray($result);
    var_dump($rows); // Array of rows
    $result->free();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件