0

I did a little research in how I could total up the values of a column in MySQL and found that SELECT SUM was the best method, however I've spent hours trying to work this out and I still can't get it to work:

Here's the code:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$result = mysqli_query('SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];

echo $sum;
mysqli_close($conn);

Here's the table:

enter image description here

3
  • Is the price column int (or something that is not text/string)? Commented Mar 19, 2017 at 8:53
  • Yes, set to int(20) Commented Mar 19, 2017 at 8:55
  • Side Note: SQL Injection... Commented Mar 19, 2017 at 9:01

2 Answers 2

2

you are connecting to database using OOP style, then trying to fetch your data using procedural style,

you need to convert your procedural to OOP;

this lines:

$result = mysqli_query('SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];

should be as follows:

$result = $conn->query('SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches'); 
$row = $result->fetch_assoc(); 
$sum = $row['value_sum'];

if you need to keep your procedural style, connect to mysqli using the procedural style:

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} 

then pass your connection to mysqli_* function as follows:

$result = mysqli_query($conn, 'SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches');
//                     ^^^^^
$row = mysqli_fetch_assoc($result); 

$sum = $row['value_sum'];
Sign up to request clarification or add additional context in comments.

Comments

0

Your query is good. Maybe your 'id' attribute isn't a numeric type ?

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.