PHP MySQL 不显示所有行 [英] Php MySQL not displaying all rows
问题描述
这是我试图显示数据库中所有数据的代码...
here is code i am trying to display all data from database...
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);
但它只显示一行..我在数据库中总共有三行,如果我在数据库中运行相同的查询,它会显示所有行..我想显示所有三行如何解决这个问题?
but it is displaying only one row.. I have totally three rows in database , if i run the same query in database, it displays all rows.. i want to display all three rows how to fix this?
推荐答案
由于您期望多行,因此需要使用 while 循环它们:
Since you're expecting multiple rows you need to loop them using while:
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row1 = mysql_fetch_assoc($sql)) {
echo $row1['column_name'];
}
强制性说明:
请不要在新代码中使用mysql_*
函数.它们不再维护并正式弃用.看到红框?了解准备好的语句,并使用PDO 或 MySQLi- 这篇文章 将帮助您决定哪个.如果您选择 PDO,这里有一个很好的教程.
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 对应方的一个简单示例:
Here is a simple example coming from PDO's counterpart:
$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 的资源不会短缺.
Basically the first answer will work but I urge you to ditch that deprecated API and start using PDO. Don't worry, you won't have shortage of sources in learning this API.
这篇关于PHP MySQL 不显示所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!