There is a table with such fields and values:

enter image description here

It is necessary that the algorithm would calculate the total amount of load (hours) for each group separately, and put these values ​​into the database.

I tried to do this:

$bd = mysql_query("SELECT * FROM list"); $pr = mysql_fetch_assoc($bd); $ch = $ch['class']; while ($res = mysql_fetch_assoc($bd)) { if($ch == $res['class']) { $ch = $res['class']; $hours = $hours + $res['count_hours']; } else 

But this seems to be wrong.

  • Агрегирующие функции - u_mulder

1 answer 1

 SELECT gruppa, sum(hours) as nagruzka FROM list GROUP BY gruppa 

And it is not NECESSARY to BORROW ANYTHING!

And just display this information with this request when required.

These are your constant iterations of the entire table with the entry in another - this is some kind of vestige left over from paper technologies. Get rid of them urgently and buy yourself a book on SQL.

Yes, and instead of mysql functions you have to use PDO.

 $sql ="SELECT gruppa, sum(hours) as nagruzka FROM list GROUP BY gruppa"; $res = $pdo->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR); 

This code will return the desired $ res array to you, in which the keys will be the names of the groups, and the values ​​will be their clock sum.

PDO is not necessary to be afraid, you just need to learn. Here is a good guide, http://phpfaq.ru/pdo
It shows that working with PDO is no more difficult than with mysql functions, especially considering that you didn’t have time to really learn them anyway.

  • I do not know how to work with PDO unfortunately. We need a simpler way out of the situation - Shamil Aslanov
  • 3
    shorty case says this is a simpler way out - Kromster
  • A significant part of the response is GROUP BY - this is the solution to your problem. :) PDO is not a prerequisite for groupings. - artoodetoo
  • @Shorty, yes, indeed your request turned out to be more convenient than the code I wrote. But he (the request) counts the total number of hours for each group. How then to do in each subject of each group? - Shamil Aslanov
  • one
    SELECT gruppa, predmet, sum (hours) from list gpoup by gruppa, predmet - Ivan