Generah Ben Generah Ben - 2 months ago 7
PHP Question

Creating dynamic table from db using php

I have tried but i could not just get where i am doing it wrong. The table only echo the first row continuously and did not echo the other rows. Kindly help please.

$run = "
SELECT * FROM staff
";
$runquery = mysqli_query($connection, $run);
$runrow = mysqli_num_rows($runquery);
if($runrow < 1){
echo "<p class='errormsg'>You do not have any Staff</p>";
}
else{
$row = mysqli_fetch_array($runquery);
if($row) {
$surname = $row['surname'];
$lastname = $row['lastname'];
$phone = $row['phone'];
$username = $row['username'];
$role = $row['auth'];
}
foreach ($row as $staff) {
$table .= "
<tr>
<td>$surname</td>
<td>$phone</td>
<td>$username</td>
<td>$role</td>
</tr>
";
}

}

Answer

You need to change loop like this. also the tabular view of your record require <table> body.

$run      = "SELECT * FROM staff";
$runquery = mysqli_query($connection, $run);
$runrow   = mysqli_num_rows($runquery);
if( $runrow < 1 ) {
    echo "<p class='errormsg'>You do not have any Staff</p>";
}
else {
    $table = ""; // create table here
    while($row = mysqli_fetch_array($runquery)) {
        $surname  = $row['surname'];
        $lastname = $row['lastname'];
        $phone    = $row['phone'];
        $username = $row['username'];
        $role     = $row['auth'];
        $table .= "<tr>
                            <td>$surname</td>
                            <td>$phone</td>
                            <td>$username</td>
                            <td>$role</td>
                        </tr>";
    }
    echo $table;
}
Comments