显示来自 MySQL 的内容仅返回一条记录


display contents from mysql return only one record

我使用此代码从 mysql 检索与 usertype="user" 行关联的所有记录

class user{
public function getnews(){
    $sql5 = "SELECT * FROM news WHERE usertype = 'user'";
    $result = mysqli_query($this->db,$sql5);
    $data = '';
    while($row = mysqli_fetch_assoc($result)){
        $data = '<article>';
        $data .= '<h3>' . $row['title'] . '</h3>';
        $data .= '<p>' . $row['content'] . '</p>';
        $data .= '<footer>By: ' . $row['whoposted'] . ' / ' . $row['dateposted'] . '</footer>'; 
        $data .= '</article>';
    }
    echo $data;
}
}

,然后显示记录。

$user = new user();
$user->getnews()

我的数据库的结构是。

id, title, content, whoposted, dateposted, usertype.

并假设我有一个 usertype="admin" 的记录

id=autoincrement, title="this is the title", content="this is the content", dateposted="2015/03/08", usertype="admin"

和 5 条用户类型="用户"的记录

id=autoincrement, title="this is the title", content="this is the content", dateposted="2015/03/08", usertype="user"

现在,正如您从我的 MySQL 查询中看到的那样,我想获取所有具有 usertype="user" 的记录,并且它假设显示除一条具有 usertype="admin" 的记录之外的所有记录,但它只显示一条记录。

有人知道我的代码出了什么问题吗?

任何帮助将不胜感激。谢谢!

你需要在

循环外声明$data,你在循环内做,因此在每个循环内它被覆盖,你得到最后一个值。

$data = '';
while($row = mysqli_fetch_assoc($result)){
        $data .= '<article>';
        $data .= '<h3>' . $row['title'] . '</h3>';
        $data .= '<p>' . $row['content'] . '</p>';
        $data .= '<footer>By: ' . $row['whoposted'] . ' / ' . $row['dateposted'] . '</footer>'; 
        $data .= '</article>';
    }