dsw7547 2018-05-06 19:29
浏览 347
已采纳

如何循环三维数组以将数据插入数据库?

This is my 3 dimensional array.

My $_POST array. These are the values

$_POST = Array ( 
[9] => Array ( [student_id] => 9 [subject_id] => 6 [class_id] => 2 [mark_obtained] => 40 [mark_obtainable] => 100 ) 
[10] => Array ( [student_id] => 10 [subject_id] => 6 [class_id] => 2 [mark_obtained] => 52 [mark_obtainable] => 100 ) 
[11] => Array ( [student_id] => 11 [subject_id] => 6 [class_id] => 2 [mark_obtained] => 30 [mark_obtainable] => 100 ) 
[12] => Array ( [student_id] => 12 [subject_id] => 6 [class_id] => 2 [mark_obtained] => 68 [mark_obtainable] => 100 ) )

How do i loop through it and submit each of the array into the database?

My column names are the keys. "student_id, subject_id, class_id, mark_obtained, mark_obtainable".

I am trying this but i keep getting duplicate entries.`foreach ($_POST as $i => $values1) {

foreach ($values1 as $key => $value) {
    $columns = implode(", ",array_keys($values1));
    $values  = implode(", ", $values1);
    $columns = $columns
    $sql = "INSERT INTO `daily_report`($columns) VALUES ($values)";

    if ($conn->multi_query($sql) === TRUE) {
        echo "New records created successfully <br>";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
  • 写回答

2条回答 默认 最新

  • draxu26480 2018-05-07 16:43
    关注

    You have to echo the sql variable inside the foreach loop like this.

    foreach ($_POST as $data => $values) {
    
    echo $sql = "INSERT INTO `daily_report` (student_id, subject_id, class_id,mark_obtained,mark_obtainable,daily_report.date)
    VALUES (".$values['student_id'].", ".$values['subject_id'].", ".$values['class_id'].", ".$values['mark_obtained'].",".$values['mark_obtainable'].", now())";
    
    // echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    

    Concatenate the variables while echoing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵