How can I use mysqli_fetch_array() twice?

You should always separate data manipulations from output.

Select your data first:

$db_res = mysqli_query( $db_link, $sql );
$data   = array();
while ($row = mysqli_fetch_assoc($db_res))
{
    $data[] = $row;
}

Note that since PHP 5.3 you can use fetch_all() instead of the explicit loop:

$db_res = mysqli_query( $db_link, $sql );
$data   = $db_res->fetch_all(MYSQLI_ASSOC);

Then use it as many times as you wish:

//Top row
foreach ($data as $row)
{
    echo "<td>". $row['Title'] . "</td>";
}

//leftmost column
foreach ($data as $row)
{
    echo "<tr>";
    echo "<td>". $row['Title'] . "</td>";
    .....
    echo "</tr>";
}

Leave a Comment