I want insert this json from jquery.ajax (content of index VALOR don't always have data):
[
{
"input": "calleFiscal",
"valor": ""
},
{
"input": "numFiscal",
"valor": "numero fiscal"
},
{
"input": "colFiscal",
"valor": ""
},
{
"input": "delefacionFiscal",
"valor": ""
},
{
"input": "estadoFiscal",
"valor": "11"
},
{
"input": "calleComercial",
"valor": "calle comercial"
},
{
"input": "numComercial",
"valor": ""
},
{
"input": "colComercial",
"valor": ""
},
{
"input": "delefacionComercial",
"valor": ""
},
{
"input": "estadoComercial",
"valor": "3"
},
{
"input": "calleEntrega",
"valor": ""
},
{
"input": "numEntrega",
"valor": ""
},
{
"input": "colEntrega",
"valor": "colonia entrega"
},
{
"input": "delefacionEntrega",
"valor": ""
},
{
"input": "estadoEntrega",
"valor": "11"
}
]
Is created by mapping a div using jquery, and I try to insert in a database with this:
$addresses = json_decode($this->dataActionClient['addresses'],true);
$sqlAd = "INSERT INTO t_direcciones_clientes (Id_Cliente,Calle,Numero,Colonia,Municipio,Estado,Tipo) VALUES (:idc,:calle,:num,:col,:deleg,:edo,:tipo)";
$resultAd = $this->dbConnect->prepare($sqlAd) or die ($sqlAd);
$fields = array('calle','num','col','deleg','edo');
$types = array('fiscal','comercial','entrega');
$resultAd->bindParam(':idc',$id_cliente,PDO::PARAM_INT);
$counType = 0;
foreach ($addresses as $key => $value) {
$key++;
$resultAd->bindParam(':'.$fields[$key], $value['valor']);
if ($key == 4 || $key == 9) {
$resultAd->bindParam(':tipo', $types[$counType]);
$counType++;
$resultAd->execute();
}
}
Explanation of that code:
I have 3 areas (fiscal, comercial, entrega) and each one has 5 inputs (Calle, Numero, Colonia, Municipio, Estado, Tipo) then I need insert 3 rows in a table and these 3 rows have the same Id_Cliente but have differente Tipo and different content of your 5 inputs. But doesn't work, and display this error:
Tried to bind parameter number 0. SQL Server supports a maximum of 2100 parameters.
Maybe my method is wrong and if exists any way to do this, I was the grateful.
Edited
I solve my problem changing some values according system functionanily but thanks to everyone.
I think you need to add 1 more counter, that you can reset to 0 after 5 loops. Try this -
$counField = 0; // counter to access field array, will be reset to 0 after 5 loops
$counType = 0;
foreach ($addresses as $key => $value) {
$resultAd->bindParam(':'.$fields[$counField], $value['valor']);
if ($key == 4 || $key == 9 || $key == 14) {
$resultAd->bindParam(':tipo', $types[$counType]);
$counType++;
$counField++; // increase if the last of 5 loops
$resultAd->execute();
}
else {
$counField++; // increase if not the last of 5 loops
}
}
here is a phpFiddle example that shows the outcome - http://phpfiddle.org/main/code/k4b-nja