使用 MySqli 和数组返回多行 [英] Returning Multiple Rows with MySqli and Arrays

查看:48
本文介绍了使用 MySqli 和数组返回多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去两天左右的时间里,我一直在将我的函数转换为 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();

}}

这里我试图显示数据.

$user_id = 1;

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

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

推荐答案

你必须使用循环来一次性获取它们:

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

这篇关于使用 MySqli 和数组返回多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆