我是PHP新手 我想从数据库中获取帖子数据,所以我创建了此功能。
function GetPosts() {
global $connection;
global $post_id;
global $post_cat_id;
global $post_authur;
global $post_date;
global $post_image;
global $post_content;
global $post_status;
global $post_tags;
global $post_title;
$query = "SELECT * FROM posts";
$get_all_posts = mysqli_query($connection, $query);
if(!$get_all_posts) {
die(mysqli_error($connection));
}
while($row = mysqli_fetch_assoc($get_all_posts)) {
$post_id = $row['post_id'];
$post_cat_id = $row['post_category_id'];
$post_authur = $row['post_authur'];
$post_title = $row['post_title'];
$post_date = $row['post_date'];
$post_image = $row['post_image'];
$post_content = $row['post_content'];
$post_status = $row['post_status'];
$post_tags = $row['post_tags'];
} }
我在posts.php文件中调用了函数,但只显示了一个帖子
<?php GetPosts(); ?>
<tr>
<td><?php echo $post_id ?></td>
<td><?php echo $post_authur ?></td>
<td><?php echo $post_title ?></td>
<td><?php echo $post_cat_id ?></td>
<td><?php echo $post_status ?></td>
<td><?php echo $post_image ?></td>
<td><?php echo $post_tags ?></td>
<td><?php echo $post_date ?></td>
我应该如何调用此函数以获取所有帖子?
答案 0 :(得分:0)
function GetPosts() {
global $connection;
$result = [];
$query = "SELECT * FROM posts";
$get_all_posts = mysqli_query($connection, $query);
if(!$get_all_posts) {
die(mysqli_error($connection));
}
while($row = mysqli_fetch_object($get_all_posts)) {
$result[] = $row;
}
return $result;
}
$posts = GetPosts();
foreach ($posts as $post) {
echo $post->post_id; // here you can access all the attributes in column
}