查询失败数据未插入数据库

这些是我的数据库上的字段

  • partamento int

  • codigocurso int

  • diurno int

  • contacto int

  • pos_laboral int

  • contacto2 int

  • proc_por int

从昨天开始我一直在尝试修复这个错误,但我无法弄清楚错误在哪里。**

foreach ($diurno as $userId) {

        $data .= "(".$id.",".$grdid.",".$userId.",".$contacto.",".$pos_laboral.",".$contacto2.",".$idd.")";

    }

    

    $data = rtrim($data, ',');

    $sql = "insert into cursosprogramas (departamento, codigocurso, diurno, contacto, pos_laboral, contacto2, proc_por) values (".$data.");";

    echo $sql;

错误


插入cursosprogramas(department, codigocurso, daytime, contact, pos_laboral, contacto2, proc_por)values((100,120,7,646,5,363,2)(100,120,4,646,5,363,2));查询失败。


白猪掌柜的
浏览 139回答 2
2回答

扬帆大鱼

您在数据集之间缺少逗号,并且也不需要将它们全部括起来。您已经在使用rtrim()删除最后一个逗号,但实际上并没有在数据集的末尾添加逗号。foreach ($diurno as $userId) {        //add a comma at the end    //note you can write variables directly into a string that is wrapped with double quotes    $data .= "('$id', '$grdid', '$userId', '$contacto', '$pos_laboral', '$contacto2', '$idd'),";}//this gets rid of the very last comma in the string$data = rtrim($data, ',');//remove parenthesis around `$data`$sql = "insert into cursosprogramas (departamento, codigocurso, diurno, contacto, pos_laboral, contacto2, proc_por) values {$data};";echo $sql;注意:Little Bobby表示这段代码可能面临 SQL 注入攻击的风险,具体取决于其中变量的$data创建方式。

牛魔王的故事

您需要在值元组之间使用逗号。尝试在第二行末尾加一个逗号,如下所示:foreach ($diurno as $userId) {$data .= "(".$id.",".$grdid.",".$userId.",".$contacto.",".$pos_laboral.",".$contacto2.",".$idd."),";}$data = rtrim($data, ',');$sql = "insert into cursosprogramas (departamento, codigocurso, diurno, contacto, pos_laboral, contacto2, proc_por) values (".$data.");";echo $sql;
打开App,查看更多内容
随时随地看视频慕课网APP