gpt4 book ai didi

Php MySQL 不显示所有行

转载 作者:行者123 更新时间:2023-12-01 00:21:05 26 4
gpt4 key购买 nike

这是我试图显示数据库中所有数据的代码...

$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);

但它只显示一行。我在数据库中总共有三行,如果我在数据库中运行相同的查询,它会显示所有行.. 我想显示所有三行如何解决这个问题?

最佳答案

由于您需要多行,因此需要使用 while 循环它们:

$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row1 = mysql_fetch_assoc($sql)) {
echo $row1['column_name'];
}

强制性说明:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

这是一个来自 PDO 对应的简单示例:

$con = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password'); // simple connection
$query = $con->query('SELECT * FROM data ORDER BY id DESC'); // put your query here
while($row = $query->fetch(PDO::FETCH_ASSOC)) { // same concept, you need to fetch them and put them inside the while loop since you're expecting multiple rows
echo $row['column_name'];
}

基本上第一个答案会奏效,但我强烈建议您放弃已弃用的 API,并开始使用 PDO。别担心,学习这个 API 不会缺少资源。

关于Php MySQL 不显示所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26340523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com