PHP Array doesn't show all the data from datab

2019-07-28 22:39发布

问题:

I have a very basic and simple script that should display records from my database. The problem: it doesn't show all the records. I've tried it even with the most simple mysql ($sql="SELECT * FROM $tbl_name";) but still some records are missing (mostly the first of the list that isn't shown).

So here is my code (it's all on 1 page):

<?php
$host="localhost";
$username="***";
$password="***";
$db_name="***";
$tbl_name="***";

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name WHERE rowNameOne >= 0.01 AND rowNameTwo='2013'";

if ($_GET['sort'] == 'one')
{
    $sql .= " ORDER BY one ASC";
}
elseif ($_GET['sort'] == 'two')
{
    $sql .= " ORDER BY two ASC";
}
elseif ($_GET['sort'] == 'three')
{
    $sql .= " ORDER BY three ASC";
}
elseif($_GET['sort'] == 'four')
{
    $sql .= " ORDER BY four ASC";
}
elseif($_GET['sort'] == 'five')
{
    $sql .= " ORDER BY five ASC";
}

$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>

<body onload="parent.alertsize(document.body.scrollHeight);"> 
<br />
<table cellspacing="0" cellpadding="0" align="center">
<tr>
<td valign="top" colspan="5">
<font>Titel</font>
</td>
<tr>
<td><a href="pageName.php?sort=one">Titel one</a></td>
<td><a href="pageName.php?sort=two">Titel two</a></td>
<td><a href="pageName.php?sort=three">Titel three</a></td>
<td><a href="pageName.php?sort=four">Titel four</a></td>
<td><a href="pageName.php?sort=five">Titel five</a></td>
</tr>
<tr>
<td colspan="5" class="noBorder">

<?php
while($rows=mysql_fetch_array($result)){
?>

<a href="pageName.php?id=<? echo $rows['id']; ?>" >
<table width="100%">
<tr>
<td><? echo $rows['rowNameOne']; ?></td>
<td><? echo $rows['rowNameTwo']; ?></td>
<td><? echo $rows['rowNameThree']; ?></td>
<td><? echo $rows['rowNameFour']; ?></td>
<td><? echo $rows['rowNameFive']; ?></td>
</tr>
</table>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
<?php
}
?>
</a>

</td>
</tr>
</table>

It's a very basic code, easy as can be I would say, but still it's missing records, not displaying everything that's in the database. What am I doing wrong?

Thanks for the help!

回答1:

Before you start the loop, you do this:

$rows=mysql_fetch_array($result);

Then the loop condition is:

while($rows=mysql_fetch_array($result)){

So the first result is never shown. I would advice to remove the first statement, since you're not using its results between that statement and the loop.

On a related note, please consider moving to PDO or mysqli.