簡體   English   中英

php-使用while調用函數

[英]php - Calling function with while

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

暫無
暫無

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

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