在PHP MySQL中获得总和

时间:2017-09-20 16:00:48

标签: mysqli

我想获得从mysql

中选择的整数之和

这是我的代码

<?php
Include 'init.php';
$page = '2459';

$ttl = array();

$search = $db->link->query("SELECT id,packid,rating FROM pakrate WHERE packid LIKE '%$q%'");

if($search->num_rows>0){
    while($result=$search->fetch_assoc()){
        $ttl[] = $row['rating'];

        echo $ttl;
        echo $result[SUM('rating')];
    }
}
else {
    echo "no such query";
}

那么我在这里做错了什么,还有其他建议吗?

1 个答案:

答案 0 :(得分:0)

只需在查询中运行总和

<?php

Include 'init.php';
$page = '2459';

$ttl = array();

// Not sure why you're doing this but there should only be one leading connection ($conn->query) unless you're doing some object item elsewhere in init.

// I would also use prepared statements since they're more secure:

$q = "%$q%";   // create your like variable, wherever $q is coming from??

$query = "SELECT sum(rating) from pakrate WHERE packid LIKE ?);
$stmt = $db->prepare($query);  // assuming $db is your connection variable
if($stmt){
   $stmt->bind_param("s",$q);  // Bind the variable in
   $stmt->execute();           // Execute
   $stmt->bind_result($rating);   // Bind the result variable
   $stmt->store_result();        // Store it so you can get num_rows
   $rows = $stmt->num_rows;    // assign rows found

   if($rows > 0){
       while($stmt->fetch()){    // Loop the result

       $ttl[] = $rating;   // add to your array

       // You can't echo an array like this.... echo $ttl;
       // if you really want to, print_r($ttl);
       }
   }
 $stmt->close(); // Close it
}

?>