I don't know why insert values in my table doesn't work using foreach to traverse Json Object.. when I see the table, fields are empty.
Json Object (from jquery.ajax)
[{"marca":"Cisco","producto":"UCS","subproducto":"Nexus"},"marca":"Citrix","producto":"Networking","subproducto":"Netscaler"}]
print_r($data)
Array
(
[0] => Array
(
[marca] => Cisco
[producto] => UCS
[subproducto] => Nexus
)
[1] => Array
(
[marca] => Citrix
[producto] => Networking
[subproducto] => Netscaler
)
)
PHP CODE
$data = json_decode($this->dataNewPoliza['alcances'], true);
$marca;
$producto;
$subproducto;
$sqlAlc = "INSERT INTO t_poliza_alcanceproductos VALUES (:idp,:m,:p,:s)";
$resultAlc = $this->dbConnect->prepare($sqlAlc) or die ($sqlAlc);
foreach ($data as $key => $value) {
foreach ($value as $mps => $valuemps) {
if($mps == 'marca') {
$marca = $valuemps;
}
if($mps == 'producto') {
$producto = $valuemps;
}
if($mps == 'subproducto') {
$subproducto = $valuemps;
}
}
$resultAlc->bindValue(':idp',$id_poliza,PDO::PARAM_INT);
$resultAlc->bindValue(':m',$marca,PDO::PARAM_INT);
$resultAlc->bindValue(':p',$producto,PDO::PARAM_INT);
$resultAlc->bindValue(':s',$subproducto,PDO::PARAM_INT);
if(!$resultAlc->execute()) {
return false;
} else {
return true;
}
}
Hope to get some help.
Solved
The problem was that I could not do return false or true within the foreach and as said @zerkms , I don't need nested loop, and this is final result:
$data = json_decode($this->dataNewPoliza['alcances'], true);
$sqlAlc = "INSERT INTO t_poliza_alcanceproductos VALUES (:idp,:m,:p,:s)";
$resultAlc = $this->dbConnect->prepare($sqlAlc) or die ($sqlAlc);
foreach ($data as $key => $value) {
$resultAlc->bindValue(':idp',$id_poliza,PDO::PARAM_INT);
$resultAlc->bindValue(':m',$value['marca'],PDO::PARAM_INT);
$resultAlc->bindValue(':p',$value['producto'],PDO::PARAM_INT);
$resultAlc->bindValue(':s',$value['subproducto'],PDO::PARAM_INT);
$resultAlc->execute();
}
return true;
Thanks for ur help!
$value['marca'], what you do with nested loop is just nonsense$value['marca']- this is how you access the array values