0

I am using Class and function, trying to send data from mysqli while loop to public $post=array(); in Class,

I dunno why while loop only save last data from mysqli

Code

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);
        }
    }

if im trying to use [] at post array, it works but it make new array 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
                    ));

My question, how to send all data from mysqli using while loop to array in Class?

Like This

2 Answers 2

2

Just use the post number as the array key on your class property $this->post instead of indexing a new array each time:

$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
);
Sign up to request clarification or add additional context in comments.

Comments

1

Since you're using $this->post = array(.... After your while loop, the last assigned value is the last record of your query.

I'm not sure how you're going to perform your saving on this. I assume that after you have your posts collection, then you will loop on it and that's where you will perform the insertion right?.

Anyhow, considering your code, you can use array_push. Like so,

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
    )));

1 Comment

This is just a slightly longer version of the second part of what he has tried already

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.