简体   繁体   English

使用MySqli和数组返回多行

[英]Returning Multiple Rows with MySqli and Arrays

For the past two days or so I've been converting my functions to mysqli. 在过去的两天左右,我一直在将我的功能转换为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?

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

为什么不直接使用这样:

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

I'm late, but I believe this is what you wanted to achieve: 我迟到了,但我相信这是你想要达到的目标:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM