Polonio
Polonio

Reputation: 23

Comparing values from a database using a while loop

I have a MySql table where I saved all workers names and the dates workers have to work on. I want to show a list containg all days of the current month and the worker names who have to work on the day that corresponds to them. Example:

February

etc.

This is the code I have in PHP but the loop is not working. I just get a list from 1 to 30 but it is not showing the data from database. If I run the loop without the (while ($n < 31)), I get all the records from database but I want to show the names just beside the day that correspond.

<?php 

mysql_select_db($database_nineras, $nineras);
$query_res = sprintf("SELECT res_id, res_dateini, res_datefin, res_name  FROM reservas ORDER BY  res_dateini DESC");
$reservas = mysql_query($query_res, $nineras) or die(mysql_error());
$rreser = mysql_fetch_assoc($reservas);
$treser = mysql_num_rows($reservas);

$n = 1;

while ($n < 31)  {
    do {
        ++$n;
        if ($n == date('d', strtotime($rreser['res_dateini']))) {
            echo $n . ' - ' . $rreser['res_name'];
        }
        else {
            echo $n;
        }
    } while ($rreser = mysql_fetch_assoc($reservas));
}
?>  

Upvotes: 0

Views: 387

Answers (1)

Barmar
Barmar

Reputation: 782181

The problem with your code is that the do-while loop is fetching all the rows returned by the query. So when you get to the second iteration of the while loop there's nothing left to fetch.

Rather than fetch the rows from the database each time through the loop, you can fetch them once and put them into an array whose index is the day numbers. Then you can loop through the days and print all the rows for each day.

Use date('j', ...) to get the date without a leading zero. Or change your SQL query to return DAY(res_dateini).

$results = array();
$reservas = mysql_query($query_res, $nineras) or die(mysql_error());
while ($rreser = mysql_fetch_assoc($reservas)) {
    $d = date('j', strtotime($rreser['res_dateini'])));
    $results[$d][] = $rreser['res_name'];
}
for ($day = 1; $day <= 31; $day++) {
    echo "$day - " . (isset($results[$day]) ? implode(", ", $results[$day]) : "") . "<br>\n";
}

DEMO

Upvotes: 1

Related Questions