Martin
Martin

Reputation: 19

First data not showing when I get data from a MySQL database

I want to show all of the data from my MySQL database to this PHP file. However, when I run the code, all of the data shows up, but the first data from the database is not showing up. I wonder is there any mistake in the code?

<?php
session_start();
include "db.php";

   echo'<table class="table table-bordered" >';
   echo"<tr>";
   echo"<td>No.</td>";
   echo"<td>Nama Masakan</td>";
   echo"<td>Jumlah</td>";
   echo"<td>Keterangan</td>";
   echo"<td></td>";
   echo"<td></td>";
   echo"<td></td>";
   echo"</tr>";

$query= mysql_query("SELECT * FROM `".$_SESSION["tabel"]."`");
if($row=mysql_fetch_row($query)>0){

   $i=1;
   
   
   while($row = mysql_fetch_array($query))
   {
       echo"<tr>";
	   echo"<td>";
	   echo $i;
	   echo"</td>";
	   echo"<td>{$row['nama_masakan']}</td>";
	   echo"<td><input type='text' name='jumlah[]' id='jumlah$i' disabled='true' value='{$row['jumlah']}'/> </td>";
	   echo"<td><input type='text' name='keterangan[]' id='keterangan$i' disabled='true' value='{$row['keterangan']}'/></td>";
	   echo"<td><button type='button' name='edit' id='edit$i' onClick='edit($i)'>Edit</button></td>";
	   echo"<td><button type='button' name='save' id='save$i' disabled='true' onClick='save($i)'>Save</button></td>";
	   echo"<td><button type='button' name='delete' id='del$i' onClick='del($i)'>Del</button></td>";
	   echo"</tr>";
	   $i++;
   } 
  
} else{
echo "Tidak ada Pesanan Makanan";	
}
 echo"</Table>";

?> 

</div>

Upvotes: 0

Views: 573

Answers (1)

Darwin von Corax
Darwin von Corax

Reputation: 5246

Obligatory chastisement: don't use the mysql API. It's deprecated and lacks numerous crucial features. Now on to my answer...

Each time you call mysql_fetch_* it retrieves the next row from the result. You call mysql_fetch_row once in your if (which fetches the first row) then again in your while (which fetches the second row) before you do anything with the row you've fetched.

In your if, instead of fetch you should be checking mysql_num_rows to determine whether you have any data:

if (mysql_num_rows($query) > 0)
{
    $i=1;

    while($row = mysql_fetch_array($query))
    {

Once you have that change working, you would be well-served to read up on the mysqli API and begin converting your code.

Upvotes: 2

Related Questions