Checkout (page) backend I am developing an e-commerce site and am confused about this.


Customers come on the site and add some products to the cart.
Customers click on the checkout link if already logged in, then will go to the "thanks" page (this is your order number, total price, etc.).


I want to insert the total price into Order table.

&lt;?php
session_start();
include('../includes/dbfunctions.php');
if(!isset($_SESSION["id"]))
{
header("location:order_login.php");
}
if(isset($_SESSION['id']))
{
$id=$_SESSION["id"];
$email=$_SESSION["email"];
$name=$_SESSION['name'];
$contact=$_SESSION["contact"];
$mysqli-&gt;query("insert into     orders(user_id,user_name,contact_no,email)values('$id','$name','$contact','$email')");

$result=$mysqli-&gt;query("select order_id from orders where user_id='$id'   ORDER BY order_id desc limit 1"); 
$obj=$result-&gt;fetch_object();
$order_id=$obj-&gt;order_id;
}
?&gt;
&lt;form action="#" method="post" enctype="multipart/form-data"&gt;
&lt;div class="table-responsive"&gt;
  &lt;?php
        //Display of cart

        if(isset($_SESSION["products"]))
        {
            $total = 0;
            $qty=0;
            ?&gt;



        &lt;?php   
        foreach ($_SESSION["products"] as $cart_itm)
        {   
            $product_qty = $cart_itm["qty"];
            $product_code=$cart_itm["product_code"];
            $image=$cart_itm["pic"];
            $product_name=$cart_itm["name"];

            echo '&lt;img src="../image/product/'.$image.'"width="120px" height="94px"&gt;';
            echo 'ucwords($product_name)';
            echo 'ucwords($product_code)';
            echo 'ucwords($product_qty)';
            $subtotal = ($cart_itm["price"]*$product_qty);
            $total = ($total + $subtotal);          
            echo '$subtotal';
            $qty=($product_qty+$qty);

            $mysqli-&gt;query("insert into order_details(user_id,img,product_name,product_code,qty,sub_total,order_id)values('$id','$image','$product_name','$product_code','$product_qty','$subtotal',$order_id)");


            }
            ?&gt;
&lt;/form&gt;
I see two obvious problems:


Your MySQLi queries are vulnerable to sql-injection since you are constructing the queries using string interpolation.  You should use properly parameterized queries with ? placeholders instead.
The business logic is heavily intertwined with the HTML generation.  You would be better off handling the input first (using PHP more like a programming language), writing the order to the database, then when the transaction has successfully completed, proceed to display the output (using PHP as a template language).