'My POS application is inserting records twice into the database [closed]

I have been trying to insert into my database but it inserts with a random behavior. Although, the code runs correctly on PHP Version 7., I'm having problems with running it on PHP Version 8.1.2.

Sometimes it inserts correctly, most times it inserts twice. That's my only challenge actually. I also tried to fix by reporting errors using || ob_start(); ini_set('display_errors', 1); || and also disabled the javascript alert but no error was displayed. I'd appreciate it if you could look at the code a little closer. I checked the error logs and there's no problem.

if(isset($_POST['submit_sales'])){
    $prd = $_POST['prd'];
    $count = count($prd);
    $rand_sales = rand(); 
    $cust_name = check_input($_POST['custname']);
    $cust_num = check_input($_POST['custnumber']);
    // echo $count;
    // Looping all files
    if($count<1){
        // $error = 'Cart is empty';
        echo '<script>alert("Cart is empty !!!");window.location="all_products.php";</script>';
        // echo '<script>window.location="all_products.php";</script>';
        
    }else{
        for($i=0;$i<$count;$i++){
            $products = $_POST['prd'][$i];
            $price = $_POST['price'][$i];
            $qty = $_POST['qty'][$i];
            
                  $fl= dbconnect()->prepare("INSERT INTO sales SET cust_name=:custname, cust_number=:custnumber, prd_name=:prd, qty=:qty, price=:price, ref_code=:random");
                  $fl->bindParam(':custname', $cust_name);
                  $fl->bindParam(':custnumber', $cust_num);
                  $fl->bindParam(':prd', $products);
                  $fl->bindParam(':qty', $qty);
                  $fl->bindParam(':price', $price);
                  $fl->bindParam(':random', $rand_sales);
                  $fl->execute();
        }
        if($fl){
            echo "<script>alert('doneit');window.location='all_products.php';</script>";
          }else {
            echo "<script>alert('Error Inserting Into Database')</script>";
          }
          
    }
}


Solution 1:[1]

I had included a script to reload the page in my header hence the double inserting, upon discarding the script, my problem was fixed. Thank you all for helping me with my challenge

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ArkDevLarry