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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler