且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

返回与库MySQLi和阵列多行

更新时间:2023-12-04 13:10:22

您必须使用一个循环,让他们一次全部:

 < PHP
功能resultToArray($结果){
    $行=阵列();
    而($行= $ result-> FETCH_ASSOC()){
        $行[] = $行;
    }
    返回$行;
}//用法
$查询=SELECT FROM`posts` WHERE`profile_user_id` = $ user_id的LIMIT 4个不同的领域$;
$结果= $ mysqli->查询($查询);
$行= resultToArray($结果);
后续代码var_dump($行); //排阵
$ result->免费();

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?

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