无法将数据保存到Mysql数据库

时间:2018-05-07 05:01:49

标签: php

我正在开发一个简单的考勤系统,其中由老师参加,然后保存到数据库。但是,我在将数据保存到数据库时遇到问题。当我点击“提交出勤”时,数据将不会提交给数据库。我使用register.php注册学生,但参加不同的文件。 以下是我用来提交的代码。有人能帮我吗?感谢。

抱歉,我共享的文件应该将数据保存到mysql数据库。下面是获取数据的文件,但仍然存在保存问题。

这是参加考试的教师档案 teacher.php

 <?php
    $pageTitle = 'Take Attendance';
    include('header.php');
    require("db-connect.php");
    if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
        echo 'Only teachers can create new teachers and students.';
        $conn->close();
        include('footer.php');
        exit;
    }
    //get session count
    $query = "SELECT * FROM attendance";
    $result = $conn->query($query);
    $sessionCount=0;
    setcookie('sessionCount', ++$sessionCount);
    if(mysqli_num_rows($result)>0){
        while($row = $result->fetch_assoc()){
            $sessionCount = $row['session'];
            setcookie('sessionCount', ++$sessionCount);
        }
    }

    if(isset($_GET['class']) && !empty($_GET['class'])){
        $whichClass = $_GET['class'];
        $whichClassSQL = "AND class='" . $_GET['class'] . "'";
    } else {
        $whichClass = '';
        $whichClassSQL = 'ORDER BY class';
    }

    echo '
        <div class="row">
            <div class="col-md-4">
                <div class="input-group">
                    <input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
                    <span class="input-group-btn">
                        <input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
                    </span>
                </div>
            </div>
            <div class="col-md-8">
                <form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
                    <select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
    ';

    // Generate list of classes.
    $query = "SELECT DISTINCT class FROM user ORDER BY class;";
    $classes = $classes = mysqli_query($conn, $query);
    if($classes && mysqli_num_rows($classes)){
        // Get list of available classes.
        echo '    <option value="">Filter: Select a class</option>';
        echo '    <option value="?class=">All classes</option>';
        while($class = $classes->fetch_assoc()){
            echo '    <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
        }
    } else {
        echo '    <option value="?class=" disabled>No classes defined.</option>';
    }

    echo '
                    </select>
                </form>
            </div>
        </div>
    ';

    $query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
    $result = $conn->query($query);
    ?>
        <table class="table table-striped">
            <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Class</th>
                <th>Present</th>
                <th>Absent</th>
            </tr>
            </thead>
            <tbody>
            <form method="post" action="save-attendance.php" id="attendanceForm">
            <?php
            if(mysqli_num_rows($result) > 0){
                $i=0;
                while($row = $result->fetch_assoc()){

                    ?>
                    <tr>
                            <td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
                            <td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
                            <td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
                            <td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
                            <td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
                    </tr>

                <?php $i++;
                }
            }
            ?>
            </form>
            </tbody>

        </table>
    <script>
    $("#submitAttendance").click(function(){
        if($("#session").val().length==0){
            alert("session is required");
        } else {
            $.cookie("sessionVal", $("#session").val());
            var data = $('form#attendanceForm').serialize();
            $.ajax({
                url: 'save-attendance.php',
                method: 'post',
                data: {formData: data},
                success: function (data) {
                    console.log(data);
                   if (data != null && data.success) {
                       alert('Success');
                   } else {
                       alert(data.status);
                   }
                },
                error: function () {
                   alert('Error');
                }
            });
        }
    });
    </script>
    <?php 
    $conn->close();
    include('footer.php');

save-attendance.
     <?php
        //include ("nav.php");
        require("db-connect.php");

        $query = "SELECT * FROM user WHERE role='student'";
        $result = $conn->query($query);

        $nameArray  = Array();

        $count = mysqli_num_rows($result);

        if(isset($_COOKIE['sessionCount'])){
            $sessionCount = $_COOKIE['sessionCount'];
        }

        //save record to db
        if(isset($_POST['formData'])) {

            //increment the session count
            if(isset($_COOKIE['sessionCount'])){
                $sessionCount = $_COOKIE['sessionCount'];
                setcookie('sessionCount', ++$sessionCount);
            }

            parse_str($_POST['formData'], $searcharray);
            //print_r($searcharray);die;
            //print_r($_POST);

            for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
            //    setcookie("checkloop", $i);;
                $name = $searcharray['name'][$i];
                $email=   $searcharray['email'][$i];
                $class =  $searcharray['class'][$i];
                $present= $searcharray['present'][$i];
                    if(isset($_COOKIE['sessionVal'])){
                        $sessionVal = $_COOKIE['sessionVal'];
                    }

                    //get class id
                    $class_query = "SELECT * FROM class WHERE name='".$class."'";
                    $class_id = mysqli_query($conn, $class_query);

                    if($class_id){
                        echo "I am here";
                        while($class_id1 = $class_id->fetch_assoc()){
                            $class_id_fin = $class_id1['id'];
                            echo $class_id['id'];
                        }
                    }
                    else{
                        echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
                    }

                    //get student id
                    $student_query = "SELECT * FROM user WHERE email='".$email."'";
                    $student_id = $conn->query($student_query);
                    if($student_id) {
                        while ($student_id1 = $student_id->fetch_assoc()) {
                            $student_id_fin = $student_id1['id'];
                        }
                    }

                    //insert or update the record
                    $query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
                     ON DUPLICATE KEY UPDATE isPresent='".$present."'";

                    print_r($query);

                    if(mysqli_query($conn, $query)){
                        echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
                    } else{
                    echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
                    }
            }
            $conn->close();
        }

1 个答案:

答案 0 :(得分:0)

您没有提供大量信息,但我从评论中了解到错误是$ sessionVal未定义。

如果未设置$ _COOKIE ['sessionVal'],请尝试:

1- print_r($ _ COOKIE)并检查是否设置了[sessionVal];

2-尝试将后备添加到:

if(isset($_COOKIE['sessionVal'])){
  $sessionVal = $_COOKIE['sessionVal'];
}
else {
  $sessionVal = 0;
}

$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;

最重要的是,没有必要检查是否设置了变量,并且没有设置回退,以防未设置。