0

Well, I'm pretty sure this is just a novice question, so please forgive me for that, but I feel like I'm losing my mind.

I have a simple MySQL rating table and I need to count rows and to sum rates values (int) with PHP PDO

$sql = "SELECT rate FROM rating_table";
$query = $db->query($sql);            

$rate_times = count($query->fetchAll()); // it works! 
echo '<p>'.$rate_times.'</p>';

$sum_rates = array_sum($query->fetchAll()); // it doesn't work!
echo '<p>'.$sum_rates.'</p>';

Thank you in advance for any suggestion

6
  • array_sum probably stumbles for a multidimensional array Commented Apr 14, 2016 at 8:57
  • Would you print here fetchAll() array out put? Commented Apr 14, 2016 at 9:00
  • @naf4me here for you: array(78) { [0]=> array(1) { ["rate"]=> int(4) } [1]=> array(1) { ["rate"]=> int(5) } [2]=> array(1) { ["rate"]=> int(3) } .... [77]=> array(1) { ["rate"]=> int(5) } } Commented Apr 14, 2016 at 9:10
  • using mysql functions sum and count is much better solution (and faster too) Commented Apr 14, 2016 at 9:16
  • Array_sum sums the array like : $a = [1,4,6,8,4]. array_sum($a) will output 23. Commented Apr 14, 2016 at 9:18

1 Answer 1

1

If I understand you right, all you have to do is to modify your sql request, this will return a single row

sql = "SELECT sum(rate) as rate_sum, count(*) as record_count FROM rating_table";
$query = $db->query($sql);            
$row = $query->fetch(PDO::FETCH_ASSOC);
if ($row) {
  $sum = $row['rate_sum'];
  $count = $row['record_count'];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.