这里是代码我试图显示数据库中的所有数据......
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);
但它只显示一行..我在数据库中共有三行, 如果我在数据库中运行相同的查询,它会显示所有行.. 我想显示所有三行如何解决这个问题?
答案 0 :(得分:6)
由于您需要多行,因此需要使用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。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择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时不会缺少资源。
答案 1 :(得分:0)
尝试while循环
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row = mysql_fetch_array($sql))
{
print_r($row);
}
答案 2 :(得分:0)
你需要循环你的查询,
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);
//错误的
使用mysqli,
$con=mysqli_connect("localhost","my_user","my_password","my_db");
//检查连接
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//执行查询
$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);
答案 3 :(得分:0)
简单易用的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);
}