简体   繁体   English

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

[英]Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. 我正在开发一个简单的出勤系统,该系统中的出勤由一位老师负责,然后保存到数据库中。 However, I am having a problem with saving the data to the database. 但是,将数据保存到数据库时遇到了问题。 when i click on "submit attendance" the data won't be submitted to the database. 当我单击“提交出勤”时,数据将不会提交到数据库。 i use register.php to register students but take the attendance in different file. 我使用register.php注册学生,但参加了不同的文件。 Below is the code i use to submit. 下面是我用来提交的代码。 Can someone help me? 有人能帮我吗? Thanks. 谢谢。

sorry the file i shared was supposed to save data to mysql database. 抱歉,我共享的文件应该将数据保存到mysql数据库。 Below is the file which takes the data and am still having the problem for saving it. 以下是获取数据的文件,但保存时仍然有问题。

this is the teacher file to take the attendance 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();
        }

You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined. 您没有提供很多信息,但是我从注释中了解到错误$ sessionVal是未定义的。

if $_COOKIE['sessionVal'] is not set, try: 如果未设置$ _COOKIE ['sessionVal'],请尝试:

1- print_r($_COOKIE) and check if [sessionVal] is set; 1- print_r($ _ COOKIE)并检查是否设置了[sessionVal];

2- Try to add a fallback to: 2-尝试向以下项添加后备:

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

or 要么

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

Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set. 最重要的是,没有必要检查是否设置了变量,如果没有设置,则没有回退。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM