How many SQL queries is too many? i have the following piece of code which is in a loop that loops between 28-31 times depending on the month selected. It’s used to change a css class depending on the date in the database. Everytime the $rows variable is called does it re-run the query? Is this code efficient?
$sql = ("SELECT * FROM dates WHERE dates.from<='".$date."' AND dates.to>='".$date."'");
$result = mysql_query($sql);
$rows = mysql_num_rows($result);
if ($rows >= 1)
{
$row = mysql_fetch_array($result);
if ($rows == 2)
$calendar .= '<td class="calendar-day-booked">';
else
{
if ($row['from'] == $date)
$calendar .= '<td class="calendar-day-from">';
elseif ($row['to'] == $date)
$calendar .= '<td class="calendar-day-to">';
else
$calendar .= '<td class="calendar-day-booked">';
}
}
else
$calendar.= '<td class="calendar-day">';
There’s no definitive answer for what’s too much, as there are so many paramters, e.g. how many users, what kind of hardware your database is on, etc.
If your question is “Will this be too slow for end users?” then you should profile the code, and see how it performs.
To answer your question about if each time $rows is assigned, is there a query, the answer is yes – you’ll run a SQL query each time you get $rows.
Subjectively, I’d say that’s inefficient. If this were my code, I’d rewrite it so that the SQL gets the whole month (e.g. set the date range accordingly), and then process the returned data in PHP, looping over the data and handling the month all at once. I’d probably loop over the returned data once, building an array that was keyed around the dates, and then implode that all together.