James Allan James Allan - 1 month ago 12
PHP Question

Posting a php foreach loop in database,data is inserting wrong

I have a cart where all my products are generated inside of a foreach loop that stores them in sessions.
And i want to post each product in my Table:orders.
But i am getting some errors.

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 46

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 54

what i am trying to post...

Array
(
[numero] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
)

[vari] => Array
(
[0] =>
[1] => 1
[2] => 2
[3] => 3
)

[desenho] => Array
(
[0] => img/1.0.png
[1] => img/1-1.png
[2] => img/1-2.png
[3] => img/1-3.png
)

[fabric] => Array
(
[0] => 1
[1] => 4
[2] => 2
[3] => 2
)

[size] => Array
(
[0] => 45
[1] => 45
[2] => 45
[3] => 50
)

[qnty] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
)

//some other arrays

[submit_post] => Enviar
)


This is my foreach loop code

I am trying to post this way...

if(isset($_POST['submit_post'])){
$date = date('Y-m-d');
$size = isset($_POST['size']) ? $_POST['size'] : array();
$numero = isset($_POST['numero']) ? $_POST['numero'] : array();
$vari = isset($_POST['vari']) ? $_POST['vari'] : array();
$desenho = isset($_POST['desenho']) ? $_POST['desenho'] : array();
$fabric = isset($_POST['fabric']) ? $_POST['fabric'] : array();
$size = isset($_POST['size']) ? $_POST['size'] : array();
$qnty = isset($_POST['qnty']) ? $_POST['qnty'] : array();
$cost = isset($_POST['cost']) ? $_POST['cost']: array();
$subtotal = isset($_POST['subtotal']) ? $_POST['subtotal'] : array();
$total = isset($_POST['total']) ? $_POST['total'] : array();
$all_products = isset($_POST['all_products']) ? $_POST['all_products'] : array();
$subT=0;

$pedido=$date." ".$_SESSION['userName']."-".$_SESSION['userLName'];
//46 $query = "SELECT * FROM almofadas WHERE id_price='$fabric'";
$result = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($result)){
$tecido=$rows['tecido'];

}

$ins_sql = "INSERT INTO orders (fabric,size,product_quantity,order_id,product_img,product_title,variante,product_cost,product_subtotal)
//54 VALUES ('$fabric', '$size' , '$qnty', '$pedido', '$desenho', '$numero', '$vari', '$cost', '$subT')";
if ($conn->query($ins_sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " ;
}
$conn->close();
}


What i am doing wrong,how i will fix this?

Answer

Your are trying to insert array instead of single item as value.

Put all your insertion code inside a foreach loop

foreach($fabric as $f)
{
    // search for index of current item
    $index = array_search($f, $fabric);

    // write your insert code here where column values should be like $fabric[$index], $size[$index] and so on. 
    // I mean you need to fetch array element by index.
}