jaydickey jaydickey - 1 year ago 81
MySQL Question

Why is mysqli_fetch_row preventing all my results from displaying?

I'm making a survey tracking website and I'm having trouble. I want to display all surveys that have been completed in the last 7 days. I'm using mysqli_fetch_row to see if any rows are retrieved, and if they are display them. If they aren't any compelted in the last 7 days, I want it to display the words "no recently compelted surveys to show."

if (!isset($_GET['sort'])) {
$sort = 'client_id';
} else {
$sort = $_GET['sort'];
if ($result = $db->query("SELECT client_id, date_added, client, email, date_sent, date_completed FROM clients NATURAL JOIN surveys WHERE date_completed BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() ORDER BY $sort")) {//shows surveys completed in the last 7 days
if (mysqli_fetch_row($result) == 0) {
echo "No recently completed surveys to show.";
} else {
echo "<table>";
echo "<tr><th><a href='portal.php?sort=client_id'>ID</a></th><th><a href='portal.php?sort=date_added'>Date Added</a></th><th><a href='portal.php?sort=client'>Client</a></th><th><a href='portal.php?sort=email'>Email</a></th><th><a href='portal.php?sort=date_sent'>Sent</a></th><th><a href='portal.php?sort=date_completed'>Completed</a></th>";
$rows = $result->num_rows;
for ($num = 0; $num < $rows; ++$num) {
$row = $result->fetch_array(MYSQLI_NUM);
$client_id = $row[0];
$date = $row[1];
$client = $row[2];
$email = $row[3];
$sent = $row[4];
$completed = $row[5];
echo "<tr>";
echo "<td>$client_id</td>";
echo "<td>$date</td>";
echo "<td>$client</td>";
echo "<td>$email</td>";
echo "<td>$sent</td>";
echo "<td><a href='survey/completed/index.php?id=$client_id'>$completed</a></td>";
echo "</tr>";
echo "</table>";

When I remove the if clause for mysqli_fetch_row, it displays ALL of the recently completed surveys, but if I leave it in, it ALWAYS leaves one out. Can anyone help?

Answer Source

You are discarding the first when you do the test. You can get the number of rows like this instead:

if ($result->num_rows == 0) {
    echo "No recently completed surveys to show.";
} else {
   // ....

Docs : mysqli_result::$num_rows

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download