I´m sending a javascript object through ajax with this structruce
[
{ name:'box', price:'20', id:'72', units : 2 },
{ name:'box2', price:'30', id:'73', units : 2 },
{ name:'box3', price:'40', id:'74', units : 2 }
]
Getting the data on the server this way
$data = json_decode(file_get_contents("php://input"),true);
$queryconst = '';
foreach($data as $key => $value){
$format[$key] = $value;
$format_keys = array_keys($format[$key]);
$newArray = $this->slashesToArray($value);
$queryconst = $queryconst.'(\''.implode("','", $newArray).'\'),';
}
$queryconst = rtrim($queryconst, ",");
$query = "INSERT INTO format (".implode(",", $format_keys).") VALUES ".$queryconst;
If the data that i`m sending has a single object
[
{ name:'box', price:'20', id:'72', units : 2 }
]
everything works fine
$query = INSERT INTO format (name,units,price,id) VALUES ('box','2','20','72')
the problem comes when the data has more than one object
[
{ name:'box', price:'20', id:'72', units : 2 },
{ name:'box2', price:'30', id:'73', units : 2 },
{ name:'box3', price:'40', id:'74', units : 2 }
]
and the query
$query = INSERT INTO format (price,name,units,product_id)
VALUES ('box','2','20','74'),('30','box2','2','74'),('40','box3','2','74')
the order fo the first object is different from the rest and the query fails
Any clue?