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