使用PHP PDO解码后,将整个JSON插入数据库

时间:2013-07-20 23:52:12

标签: php json pdo foreach insert

我想从jquery.ajax插入这个json(索引VALOR的内容并不总是有数据):

[
{
    "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"
}
]

通过使用jquery映射div来创建,我尝试使用以下内容插入数据库:

$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();
    }
}

该代码的说明:

我有3个区域(财政,商业,企业),每个区域有5个输入(Calle,Numero,Colonia,Municipio,Estado,Tipo)然后我需要在表格中插入3行,这3行具有相同的 Id_Cliente ,但具有不同的 Tipo 以及5个输入的不同内容。 但是不起作用,并显示此错误:

Tried to bind parameter number 0. SQL Server supports a maximum of 2100 parameters.

也许我的方法是错的,如果有任何办法可以做到这一点,我很感激。

被修改

我解决了我根据系统功能更改某些值的问题,但感谢所有人。

1 个答案:

答案 0 :(得分:1)

我认为你需要再添加1个计数器,你可以在5个循环后重置为0。试试这个 -

$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 
    }
}

这是一个显示结果的phpFiddle示例 - http://phpfiddle.org/main/code/k4b-nja