Php 而循环Mysqli不';不能保存在数组中
我正在使用Php 而循环Mysqli不';不能保存在数组中,php,mysqli,Php,Mysqli,我正在使用类和函数,试图在循环时将数据从mysqli发送到public$post=array()在类中 我不知道为什么while loop只保存mysqli 代码 class Post extends Connection{ public $post=array(); function selectPost(){ $query="select * from posts"; $mysqli=$this ->
类
和函数
,试图在循环时将数据从mysqli发送到public$post=array()代码>在类中
我不知道为什么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);
}
}
如果我试图在post数组中使用[],它可以工作,但会生成新数组
我的问题是,如何使用while loop
将mysqli
中的所有数据发送到类中的数组
只需使用post编号作为类属性上的数组键$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
);
只需将post编号用作类属性$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循环之后,最后分配的值就是查询的最后一条记录
我不确定您将如何在此上执行保存。我假设在您拥有posts集合后,您将在其上循环,并在那里执行插入,对吗
无论如何,考虑到您的代码,您可以使用数组\u 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
)));
由于您使用的是$this->post=array(…。在while循环之后,最后分配的值就是查询的最后一条记录
我不确定您将如何在此上执行保存。我假设在您拥有posts集合后,您将在其上循环,并在那里执行插入,对吗
无论如何,考虑到您的代码,您可以使用数组\u 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
)));
这只是他已经尝试过的第二部分的稍长版本这只是他已经尝试过的第二部分的稍长版本