Search code examples
phpwhile-loopmysql-num-rows

Usage of mysql_num_rows inside a While loop


I have a query selecting a group of matching elements, and then a If condition ckecking if one (or more) of those matching elements are valid, depending on what they contain on a couple of DATE fields. This works correctly:

$allClasses=mysql_query("SELECT * FROM class_conf WHERE cl_fk_te_id='$te_id' && cl_status='1'");
$identifiedClassId="";

 while($registros = mysql_fetch_array($allClasses)){

     $start_date=$registros['cl_startDate'];
     $end_date=$registros['cl_endDate'];

     $start_year=substr($start_date, 6, 4);
     $end_year=substr($end_date, 6, 4);
     $start_month=substr($start_date, 3, 2);
     $end_month=substr($end_date, 3, 2);
     $start_day=substr($start_date, 0, 2);
     $end_day=substr($end_date, 0, 2);

     if(($start_year  <=  $year) && ($end_year  >=  $year) && ($start_month  <=  $month) && ($end_month  >=  $month) && ($start_day  <=  $day) && ($end_day  >=  $day)) {

            $identifiedClassId=$registros['cl_id'];
     }

 }

Now I need to use something like mysql_num_rows in order to check the total amount of elemnts matching this If condition, and I do not know what query to apply on mysql_num_rows, as this query (mysql_num_rows($allClasses)) would result in the amout of matching elements before applying the If.

How can I obtain the total amount of elements matching the If condition?


Solution

  • Here is the code that should be used: It is untested. It sets the count of the number of rows returned by the query, into, $totalElements.

    Added the count of all assignments to the $identifiedClassId which i suspect will not be correct.

    $allClasses=mysql_query("SELECT * FROM class_conf WHERE cl_fk_te_id='$te_id' && cl_status='1'");
    $totalElements = mysql_num_rows($allClasses); // count of the elements 
    $identifiedClassId="";
    $countIdentifiedClassId = 0;
    
     while($registros = mysql_fetch_array($allClasses)){
    
         $start_date=$registros['cl_startDate'];
         $end_date=$registros['cl_endDate'];
    
         $start_year=substr($start_date, 6, 4);
         $end_year=substr($end_date, 6, 4);
         $start_month=substr($start_date, 3, 2);
         $end_month=substr($end_date, 3, 2);
         $start_day=substr($start_date, 0, 2);
         $end_day=substr($end_date, 0, 2);
    
         if(($start_year  <=  $year) && ($end_year  >=  $year) && ($start_month  <=  $month) && ($end_month  >=  $month) && ($start_day  <=  $day) && ($end_day  >=  $day)) {
    
                $identifiedClassId=$registros['cl_id'];
                $countIdentifiedClassId++;
         }
     }