Achy Achy - 5 months ago 8
PHP Question

Inserting data to mysql, only first date will be inserted

So, i have a little problem with this code. Its working fine, but if i try to insert two (or more...) data, its just only first data will be inserted. How can i fix this problem?

<?php
error_reporting(E_ERROR);
session_start();
include("db_config.php");
if(isset($_SESSION['login_user']))
{
$username=$_SESSION['login_user'];
$sql[0] = "SELECT * from orders where username='$username'";
$result= mysqli_query($conn,$sql[0]) or die(mysqli_error());

if (mysqli_num_rows($result)>0)
{
while ($record = mysqli_fetch_array($result))
{
$name =$record[username];
$id = $record[id];
$nmb_products = $record[nmb_products];
$total_value = $record[total_value];
$order_date = $record[order_date];
$city = $record[dest_city];
$address = $record[address];
}
}
else echo "Failed Access";

$sql[1] = "INSERT INTO ordered (username,nmb_products,product_id,total_value, city, address) VALUES ('$name', '$nmb_products', '$id', '$total_value', '$city', '$address')";
$sql[2] = "DELETE FROM orders WHERE username='$username'";
if(mysqli_query($conn, $sql[1]) && mysqli_query($conn, $sql[2]))
{
header("Location:mypurchases.php");
exit();
}
}
else
echo"Login first";

$conn->close();
?>

Answer

All of this part :

  $sql[1] = "INSERT INTO ordered (username,nmb_products,product_id,total_value, city, address) VALUES ('$name', '$nmb_products', '$id', '$total_value', '$city', '$address')";
$sql[2] = "DELETE FROM orders WHERE username='$username'";
if(mysqli_query($conn, $sql[1]) && mysqli_query($conn, $sql[2]))
{ 
    header("Location:mypurchases.php");
    exit();
} 

Might be in this loop :

if (mysqli_num_rows($result)>0)
{
    while ($record = mysqli_fetch_array($result))
    {
        $name =$record[username];
        $id = $record[id];
        $nmb_products = $record[nmb_products];
        $total_value = $record[total_value];
        $order_date = $record[order_date];
        $city = $record[dest_city];
        $address = $record[address];
    }
}

Like :

if (mysqli_num_rows($result)>0)
{
    while ($record = mysqli_fetch_array($result))
    {
        $name =$record[username];
        $id = $record[id];
        $nmb_products = $record[nmb_products];
        $total_value = $record[total_value];
        $order_date = $record[order_date];
        $city = $record[dest_city];
        $address = $record[address];



        $sql[1] = "INSERT INTO ordered (username,nmb_products,product_id,total_value, city, address) VALUES ('$name', '$nmb_products', '$id', '$total_value', '$city', '$address')";
        $sql[2] = "DELETE FROM orders WHERE username='$username'";
        if(mysqli_query($conn, $sql[1]) && mysqli_query($conn, $sql[2]))
        { 
            /*header("Location:mypurchases.php");
            exit();*/
            //Do something
        } 
    }
}