使用pdo将multidiamenstional数组插入mysql

时间:2015-04-08 14:18:24

标签: php mysql pdo

我有一个多维数组要插入到mysql表中。尝试添加日期时间以及该数组中的其他元素。 但每次我得到这个错误。 :

  

注意:未定义的偏移量:第47行的C:\ xampp \ htdocs \ Auto-attendance \ main \ proccess_attendance.php中的10

     

致命错误:未捕获异常'PDOException',消息'SQLSTATE [23000]:完整性约束违规:1048列'att_status'在C:\ xampp \ htdocs \ Auto-attendance \ main \ proccess_attendance.php中不能为空': 60堆栈跟踪:#0 C:\ xampp \ htdocs \ Auto-attendance \ main \ proccess_attendance.php(60):PDOStatement->执行(数组)#1 {main}抛出C:\ xampp \ htdocs \ Auto-第60行的出勤\ main \ proccess_attendance.php

我不知道问题在哪里。

<?php

 require_once("db_const.php");
if (!$_SERVER['REQUEST_METHOD']=='POST' 
    || !$_POST['submit']=='save'
    || empty($_POST['subject_name'])
    || empty($_POST['subject_code'])        
    || empty($_POST['department_name'])
    || empty($_POST['department_short_name'])
    || empty($_POST['teacher_name'])        
    || empty($_POST['date'])        
    || empty($_POST['time'])        
    || empty($_POST['student']) 
    || empty($_POST['stroll'])  
    || empty($_POST['status'])      

    ) {
header('Location: ../student_attendance.php?page=take-attendance');
} else {
## connect mysql server
/** $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
    echo "<p>MySQL error no {$mysqli->connect_errno} :     
 {$mysqli->connect_error}</p>";
    exit();
   }**/ 
## query database
# prepare data for insertion       538 072 662  2716
$subject_name               = $_POST['subject_name'];
$subject_code               = $_POST['subject_code'];
$department_name            = $_POST['department_name'];
$department_short_name      = $_POST['department_short_name'];
$teacher_name               = $_POST['teacher_name'];
$date                       = $_POST['date'];
$time                       = $_POST['time'];
$student                    = $_POST['student'];
$student_roll               = $_POST['stroll'];
$status                     = $_POST['status'];

$date=date_create_from_format("j-M-Y", $date);
$date= date_format($date,"Y-m-d");

$timestamp = date('Y-m-d H:i:s');


 foreach($student as $k=>$v){ 
    $st[] = array($subject_name,  $subject_code, $department_name,    
  $department_short_name, $teacher_name, $date,  $time, $timestamp,  $v, 
  $student_roll[$k], $status[$k]); }


  $db = new PDO('mysql:host=localhost;dbname=auto_attendance', 'root', 
  '');
   $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

   $insert = $db->prepare(
    'INSERT INTO student_attendance (subject_name , subject_code,   
     department_name, department_short_name,
 teacher_name, date, time, timestamp, student_name, student_roll, 
 att_status) VALUES (?, ?, ?, ?, ?, ?, ?,  ?, ?, ?, ?)');


  foreach($st as $values) {
  $result = $insert->execute($values);

   }

   if($result == true) {
    echo "<script>alert('Record successfuly 
    Saved.');window.location.href='../student_attendance.php?page=take-
    attendance';</script>";

      }

    else  {
    echo "<script>alert('Record couldnt be 
   Saved.');window.location.href='../student_attendance.php?page=take-
   attendance';</script>";

    } 


   } 
   ?>   

2 个答案:

答案 0 :(得分:2)

你的代码有点混乱,所以我尽可能多地清理:

1。我更改了你的if语句,以便它更具可读性,我删除了else部分,因为如果没有设置,你会重定向。

2。在每次exit();通话后再加header()。确保脚本执行停止。

3。我还将数据库内容包装到try and catch块中以捕获PDOExceptions

4。我还更改了execute()调用的分配,因为您要检查每个执行是否成功而不仅仅是最后一个

<?php 

    require_once("db_const.php");

    function checkPostIndex(array $indexes = [""]) {
        if(empty($indexes)) return FALSE;
        return array_reduce($indexes, function($result, $v){
            return $result && !empty($_POST[$v]);
        }, TRUE);
    }


    $indexes = ["subject_name", "subject_code", "department_name", "department_short_name", "teacher_name", "date", "time", "student", "stroll", "status"];

    if($_SERVER["REQUEST_METHOD"] !== "POST" || $_POST['submit'] !== "save" || checkPostIndex($indexes)) {
        header("Location: ../student_attendance.php?page=take-attendance");
        exit();
    }

    $subject_name               = $_POST['subject_name'];
    $subject_code               = $_POST['subject_code'];
    $department_name            = $_POST['department_name'];
    $department_short_name      = $_POST['department_short_name'];
    $teacher_name               = $_POST['teacher_name'];
    $date                       = $_POST['date'];
    $time                       = $_POST['time'];
    $student                    = $_POST['student'];
    $student_roll               = $_POST['stroll'];
    $status                     = $_POST['status'];

    $date = DateTime::createFromFormat("j-M-Y", $date)->format("Y-m-d");
    $timestamp = date("Y-m-d H:i:s");


    foreach($student as $k => $v) { 
        $tmpOne = (!empty($student_roll[$k])?$student_roll[$k]:"");
        $tmpTwo = (!empty($status[$k])?$status[$k]:"");
        $st[] = [$subject_name,  $subject_code, $department_name, $department_short_name, $teacher_name, $date,  $time, $timestamp,  $v, $tmpOne, $tmpTwo];
    }


    try {

        $db = new PDO("mysql:host=localhost;dbname=auto_attendance", "root", "");
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $insert = $db->prepare('INSERT INTO student_attendance
                                (subject_name , subject_code, department_name, department_short_name, teacher_name, date, time, timestamp, student_name, student_roll, att_status)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');

        foreach($st as $values) {
            $result[] = $insert->execute($values);
        }

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>

    <script>alert('Record <?php echo (!in_array("FALSE", $result, true)?"successfuly":"couldnt be") ?> Saved.');window.location.href='../student_attendance.php?page=take-attendance';</script>

旁注:

在文件顶部添加error reporting以获取有用的错误消息:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
?>

(仅在测试时开启,从未投入生产!)

答案 1 :(得分:0)

问题在于将值传递给$ _POST ['status'];如果你追踪传入这个变量的内容,你会发现它就是问题!