[英]While loop Mysqli doesn't save in array
我正在使用Class
和function
,试图从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 loop
从mysqli
发送所有数据到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.