[英]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? 但它只显示一行。.我在数据库中总共有三行,如果我在数据库中运行相同的查询,它将显示所有行..我想显示所有三行如何解决此问题?
Since you're expecting multiple rows you need to loop them using while: 由于您期望多行,因此需要使用while循环它们:
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row1 = mysql_fetch_assoc($sql)) {
echo $row1['column_name'];
}
Obligatory Note: 强制性说明:
Please, don't use
mysql_*
functions in new code . 请不要在新代码中使用mysql_*
函数 。 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. 相反,要了解准备好的语句 ,并使用PDO或MySQLi- 本文将帮助您确定哪一个。 If you choose PDO, here is a good tutorial . 如果您选择PDO, 这是一个很好的教程 。
Here is a simple example coming from PDO's counterpart: 这是来自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'];
}
Basically the first answer will work but I urge you to ditch that deprecated API and start using PDO. 基本上第一个答案会起作用,但我敦促您放弃已弃用的API,并开始使用PDO。 Don't worry, you won't have shortage of sources in learning this API. 不用担心,在学习此API时不会缺少资源。
Try while loop 尝试while循环
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row = mysql_fetch_array($sql))
{
print_r($row);
}
u need to loop ur query, 您需要循环查询
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);
// wrong one //错误的一个
use mysqli, 使用mysqli,
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection //检查连接
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform query //执行查询
$sql = mysqli_query($con,"SELECT * FROM data ORDER BY id DESC");
$mainarr=array();
while($row = mysql_fetch_assoc($sql)) {
$subarr=array();
$subarr['key']=$row['your field'];
array_push($mainarr,$subarr);
}
print_r($mainarr);
its simple to use mysqli just try the following once 简单易用的mysqli只需尝试以下一次
$mysqli = new mysqli("localhost", "username", "password", "database");
$strr = "SELECT * FROM data ORDER BY id DESC"; // its a good practice to use column name insted of *
$result = $mysqli->query($strr);
while($arr = $result->fetch_array())
{
print_r($arr);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.