How to sum total price in php?

i have a php function where in i want to hold a total of all the products purchased. here i am getting the cart items and i am calling the function which should hold total amount. i am passing the value

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
5 each time when i retrieve the product from cart.

for example for first item iteration i send value 300, and for second 400, for third 900.

i want to add up all these and get total price of 1600 in

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
6
how can i do this?

function getCartitems($product_id){
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT product_id,product_name,product_price,product_image_url FROM product_list WHERE product_id='$product_id'";
    $result = $conn->query($sql);      
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {              
        echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
        $price = $row['product_price'];
        payableAmount($price);      
        }
    } else {
        echo "There are no such items";
    }   
    $conn->close();
}

function payableAmount($totalPrice){    
   // calculate total price here
    $total = $totalPrice;
    echo $total;
}

Best Solution

You just simply update your query instead like as

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}

Related Solutions

Php – How to prevent SQL injection in PHP

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

  1. Using PDO (for any supported database driver):

     $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    
     $stmt->execute([ 'name' => $name ]);
    
     foreach ($stmt as $row) {
         // Do something with $row
     }
    
  2. Using MySQLi (for MySQL):

     $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
     $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
    
     $stmt->execute();
    
     $result = $stmt->get_result();
     while ($row = $result->fetch_assoc()) {
         // Do something with $row
     }
    

If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example,

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
7 and
$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
8 for PostgreSQL). PDO is the universal option.


Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
9 when something goes wrong. And it gives the developer the chance to
 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
0 any error(s) which are
 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
1n as
 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
2s.

What is mandatory, however, is the first

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
3 line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
4 in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.


Explanation

The SQL statement you pass to

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
5 is parsed and compiled by the database server. By specifying parameters (either a
 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
6 or a named parameter like
 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
7 in the example above) you tell the database engine where you want to filter on. Then when you call
 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
8, the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

 $stmt->execute([ 'name' => $name ]);

 foreach ($stmt as $row) {
     // Do something with $row
 }
9 variable contains
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
0 the result would simply be a search for the string
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
1, and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here's an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);

Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
   $dir = 'ASC';
}

Php – Deleting an element from an array in PHP

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Deleting a single array element

If you want to delete just one array element you can use

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2 or alternatively
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
3.

If you know the value and don’t know the key to delete the element you can use

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
4 to get the key. This only works if the element does not occur more than once, since
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
5 returns the first hit only.

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // Do something with $row } 2

Note that when you use

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2 the array keys won’t change. If you want to reindex the keys you can use
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
8 after
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2, which will convert all keys to numerically enumerated keys starting from 0.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
          // ↑ Key which you want to delete

Output:

[
    [0] => a
    [2] => c
]

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // Do something with $row } 3 method

If you use

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
3 the keys will automatically be reindexed, but the associative keys won’t change — as opposed to
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
8, which will convert all keys to numerical keys.

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
3 needs the offset, not the key, as the second parameter.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
                   // ↑ Offset which you want to delete

Output:

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
0

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
4, same as
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2, take the array by reference. You don’t assign the return values of those functions back to the array.

Deleting multiple array elements

If you want to delete multiple array elements and don’t want to call

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2 or
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
3 multiple times you can use the functions
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
8 or
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
9 depending on whether you know the values or the keys of the elements which you want to delete.

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 8 method

If you know the values of the array elements which you want to delete, then you can use

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
8. As before with
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2 it won’t change the keys of the array.

Code:

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
1

Output:

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
2

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 9 method

If you know the keys of the elements which you want to delete, then you want to use

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
9. You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

Code:

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
3

Output:

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}
2

If you want to use

 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
2 or
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
 $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

 $stmt->execute();

 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
3 to delete multiple elements with the same value you can use
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);
7 to get all the keys for a specific value and then delete all elements.

How to calculate total amount in PHP?

Answer: Use the PHP array_sum() function You can use the PHP array_sum() function to calculate the sum of all the numeric values in an array.

How do you calculate total price?

Total Price Formula To calculate the total price, multiply the number of items purchased by the average price per item.

How to calculate value in PHP?

PHP has a set of math functions that allows you to perform mathematical tasks on numbers..
PHP pi() Function. The pi() function returns the value of PI: ... .
PHP min() and max() Functions. ... .
PHP abs() Function. ... .
PHP sqrt() Function. ... .
PHP round() Function..

How to calculate price from database in PHP?

The code use MySQLi SUM() query to automatically calculate the price data in the database before displaying it to the HTML page.