簡體   English   中英

使用MySqli和數組返回多行

[英]Returning Multiple Rows with MySqli and Arrays

在過去的兩天左右,我一直在將我的功能轉換為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 ();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM