Php 使用MySqli和数组返回多行

Php 使用MySqli和数组返回多行,php,arrays,mysqli,Php,Arrays,Mysqli,在过去的两天左右,我一直在将我的函数转换为mysqli。我遇到了一个问题。我有一个函数,它返回一个数组,其中包含数据库中的一行。但是,我希望数组包含多行而不是一行。还有,我怎样才能回应这些帖子呢。这是我失败的尝试,它只显示数组中的一行 $mysqli = new mysqli("localhost", "user", "password", "database"); function display_posts ($mysqli, $user_id) { $fields = "`

在过去的两天左右,我一直在将我的函数转换为mysqli。我遇到了一个问题。我有一个函数,它返回一个数组,其中包含数据库中的一行。但是,我希望数组包含多行而不是一行。还有,我怎样才能回应这些帖子呢。这是我失败的尝试,它只显示数组中的一行

$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?

您必须使用一个循环一次获取所有这些数据:

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

为什么不这样直接使用:

$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);

我迟到了,但我相信这就是你想要实现的:

$mysqli = new mysqli("localhost", "user", "password", "database");
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";

function display_posts () {

    global $mysqli;
    global $fields;

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

    $posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);

    if ($posts -> num_rows > 0) {

        while ($row = $posts -> fetch_assoc()) {

        $value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];

        echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';

        }

    }else {

        echo 'No records found.';

    }

}

//Call the function
display_posts ();

虽然我希望得到一个答案,如何呼应出每一个人的价值观,但我还是自己去想。谢谢你的帮助。我决定取出函数resultToArray并将其附加到我的原始函数中。最糟糕的做法!!,既然MYSQL默认可以这样做,为什么还要将工作传递给PHP呢。请看下面我的答案。@KateGregory实际上没有什么要解释的。除此之外,该函数仅在5.3版之后才可用,并且仅在mysqlnd下可用。没有太多解释。使用可用的mysqli方法获得整个结果集,而不是执行一个while循环。同时避免为它声明一个额外的函数。是的,它高于5.3。但据我所知,mysqli也是5.3版本,而且你不想让你的$mysqli成为全球性的。这是一个巨大的安全风险。