【问题标题】:display contents from mysql return only one record从mysql显示内容只返回一条记录
【发布时间】:2015-03-08 17:35:12
【问题描述】:

我正在使用此代码从 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 条用户类型为“user”的记录

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

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

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

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

【问题讨论】:

  • 连接运算符 (.=) 在 while 循环中缺少第一行 $data = '&lt;article&gt;'; 应该是 $data .= '&lt;article&gt;';

标签: php mysql


【解决方案1】:

你需要在循环外声明$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>';
    }

【讨论】:

  • 仍然只显示一条记录。 :(
  • 感谢您的回答。我添加了 $data = "";之前 while 然后移动 echo $data;在 while 语句中。
  • 如果你有多个记录,那么它应该显示多个记录。尝试通过在循环中回显某些内容来进行一些测试,看看它是否被多次显示,同时在 mysql 中执行查询,看看是否有多个记录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2016-05-22
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多