簡體   English   中英

While循環Mysqli不保存在數組中

[英]While loop Mysqli doesn't save in array

我正在使用Classfunction ,試圖從mysqli while loop發送數據到public $post=array(); Class

我不知道為什么while loop只保存mysqli最后一個數據

class Post extends Connection{

        public $post=array();

        function selectPost(){
            $query="select * from posts";
            $mysqli=$this -> connect();
            $select_all_post=$mysqli->query($query);
            $x=1;
            while($row=$select_all_post->fetch_object()){  
                $this->post = array( 'Post No   ' . $x=> array(
                    'post_title' => $row->post_title,
                    'post_author' => $row->post_author,
                    'post_date' => $row->post_date,
                    'post_content' => $row->post_content
                ));
                $x++;
            }
            echo print_r($this->post);
        }
    }

如果我試圖在帖子數組上使用[],它可以工作,但是會創建新數組Check Output

$this->post[] = array( 'Post No   ' . $x=> array(
                        'post_title' => $row->post_title,
                        'post_author' => $row->post_author,
                        'post_date' => $row->post_date,
                        'post_content' => $row->post_content
                    ));

我的問題,如何使用while loopmysqli發送所有數據到Class array

像這樣

只需將帖子號用作類屬性$this->post上的數組 ,而不是每次都索引一個新數組:

$this->post['Post No ' . $x] = array(
    'post_title' => $row->post_title,
    'post_author' => $row->post_author,
    'post_date' => $row->post_date,
    'post_content' => $row->post_content
);

由於您使用的是$ this-> post = array(...。在while循環之后,最后分配的值是查詢的最后一條記錄。

我不確定您將如何執行此操作。 我假設在您擁有發帖集之后,您將在其上循環播放,那是您執行插入的地方嗎?。

無論如何,考慮到您的代碼,您可以使用array_push 像這樣

array_push($post, array( 'Post No ' . $x=> array(
        'post_title' => $row->post_title,
        'post_author' => $row->post_author,
        'post_date' => $row->post_date,
        'post_content' => $row->post_content
    )));

暫無
暫無

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

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