gpt4 book ai didi

php - 使用 while 调用函数

转载 作者:行者123 更新时间:2023-11-29 17:20:18 33 4
gpt4 key购买 nike

我是 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>

我应该如何调用这个函数来获取所有帖子?

最佳答案

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
}

关于php - 使用 while 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297655/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com