简体   繁体   中英

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. 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. 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.

if $_COOKIE['sessionVal'] is not set, try:

1- print_r($_COOKIE) and check if [sessionVal] is set;

2- Try to add a fallback to:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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