我正在尝试从mysql获取数据并使用while循环显示它们。但是问题出在while循环内,我得到的数据总是少一个。 假设我的数据库中有两行,但是使用此代码,我只会得到一行。第一行总是丢失。弄清楚为什么!共享一些代码。
尝试var_dump(),它显示db中有正确的数字行
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
答案 0 :(得分:2)
您正在使用while循环之前获取一行,而您不在任何地方使用while循环,这就是您丢失一行的原因。
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
答案 1 :(得分:1)
尝试删除此行:
$data = mysql_fetch_array($ddaa);
答案 2 :(得分:0)
您的代码中缺少服务器和数据库凭据,请尝试执行此操作
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
答案 3 :(得分:0)
它将为我工作。试试这个...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>