Always I sent json object to the server (php) to save in the database but always sent only one object.
Now no need to send a json array and therein lies the problem.
I can not make foreach work to save the attributes in the database (MySQL).
In JavaScript is done as follows:
This is just one example (wrong by the way), but in my json the code is correct → {id: 1, name: ‘test’}
I add this object to a variable → arrayExample.push (objectJsonExample);
This object (with added push), send to php.
Sorry for these basic errors, I write here at night forum and was tired. In my original code is correct. The foreach does not work properly.
This should not work? :
foreach ($arr as $item) {
echo $item['example'];
}
<?php
header('Access-Control-Allow-Origin: *');
require('conn.php');
// Atribuição de valores
if (isset($_REQUEST['pedido'])) {
$pedido = ($_REQUEST['pedido']);
}
else {
$pedido = '';
}
$arr = json_decode($pedido, true);
// Criar conexão
$conn = new mysqli($servername, $username, $password, $dbname);
// Checar conexão
if ($conn->connect_error)
die("Erro conexão: " . $conn->connect_error);
else
{
// YYYY-MM-DD
$dataPedido = date('Y-m-d H:i:s');
foreach ($arr as $obj) {
$sql = "INSERT INTO PEDIDOS (FK_ID_PRODUTO, PRECO)
VALUES ('".$obj['id_produto']."','"
.$obj['valor']."')";
// Registro inserido com sucesso
if ($conn->query($sql) === TRUE)
$validar = true;
else
$validar = false;
}
// Empacotamento Json
echo json_encode(array('validar' => $validar));
$conn->close();
}
?>
Quickly explaining the operation: When you click the button, I add the object to $ scope.carrinhoCompras, which will later be sent to the php and driven at foreach.
Sorry indentation, when pasting the code here is mangled.