Reputation: 753
Im using a datatable to show records from a DB, using PHP.
See my code below;
<table class="table datatable-basic">
<thead>
<tr>
<th> ID </th>
<th> Name</th>
<th>Address </th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
<?
$result9023=mysql_query("SELECT * FROM hr_locations")or die('ERROR 315' );
$num_rows = mysql_num_rows($result9023);
for ($i = 1; $i <= mysql_num_rows($result9023); $i++) {
$row = mysql_fetch_array($result9023);
$location_id = $row ['id'];
$name = $row ['location'];
$address = $row ['address'];
echo " <tr>
<td>$location_id</td>
<td>$name</td>
<td>$address</td>
<td class='text-center'>Edit</td>
</tr>
"; } ?>
</tbody>
</table>
The table is showing correctly, with the data populated as it should however I am getting the below error when the page loads.
I have looked at https://datatables.net/tn/4 however it's not making much sense?
Upvotes: 1
Views: 355
Reputation: 34416
Since most MySQL array start with 0 do this:
for ($i = 0; $i < $num_rows; $i++) {
Set $i = 0
then state that $i
must be less than the number of rows (if you have 4 you will get 0,1,2,3 (4 rows, properly indexed). Instead of counting the rows again, just use the variable you already set for the count.
You're actually probably doing a little too much with your code. Instead of using an unnecessary for loop, just use a while:
while($row = mysql_fetch_array($result9023)){
$location_id = $row ['id'];
$name = $row ['location'];
$address = $row ['address'];
echo " <tr>
<td>$location_id</td>
<td>$name</td>
<td>$address</td>
<td class='text-center'>Edit</td>
</tr>
"; } ?>
This way you're making sure to catch each row returned from your query without possibly duplicating or skipping rows as you might do when using a for loop along with mysql_fetch_array()
as you're trying to do.
Upvotes: 2