在数据库中插入PHP中数组的增量索引值时出错

时间:2018-02-07 13:33:33

标签: php mysql arrays

我需要什么

我有一个包含不同字符串的数组$ data [0到27]。我想在数据库中一次插入$ data []字符串,即,

$data[0 to 7] //insert in database, loop1

$data[7 to 13] //insert in database, loop2

$data[14 to 20] //insert in database, loop3

$data[21 to 27] //insert in database, loop4

我做了什么

    $counttr=3
    $positionCounter=0;
        for($j=0;$j<$counttr;$j++){
            $insert="insert into latest_government_jobs (post_date,exam_date,total_vacancy,qualification,advt_no,last_date,details)
 values ('$data[$positionCounter]','$data[$positionCounter+1]','$data[$positionCounter+2]','$data[$positionCounter+3]','$data[$positionCounter+4]','$data[$positionCounter+5]','$data[$positionCounter+6]')";
            mysqli_query($con,$insert);
            $positionCounter=$positionCounter+7;
        }

我的目标

我&#39;我得错误 -

  

解析错误:语法错误,意外&#39; +&#39;,期待&#39;]&#39; .....

任何人都可以帮忙向我展示如何以正确的方式编写它?

1 个答案:

答案 0 :(得分:2)

您将变量括在引号内,请参阅以下代码:

$counttr=3
$positionCounter=0;
    for($j=0;$j<$counttr;$j++){
        $insert="insert into latest_government_jobs (post_date,exam_date,total_vacancy,qualification,advt_no,last_date,details)
values ('".$data[$positionCounter]."','".$data[$positionCounter+1]."','".$data[$positionCounter+2]."','".$data[$positionCounter+3]."','".$data[$positionCounter+4]."','".$data[$positionCounter+5]."','".$data[$positionCounter+6]."')";
        mysqli_query($con,$insert);
        $positionCounter=$positionCounter+7;
    }

}

PS:你的代码有sql注入问题。请参阅此here