簡體   English   中英

ajax將php變量插入數據庫

[英]ajax to insert php variables into database

我正在研究學生出勤率。 我想為此目的使用AJAX,但無法將數據插入數據庫。 以下是我的代碼:

HTML:

<a id="Present" href="#" class="btn btn-md btn-success" onClick="Present(<?php echo $id_1; ?>);">Present</a><br/><br/>

Javascript:

<script>
function Present(Pid){
    var Pyear = <?php echo $selected_year; ?>;
    var Pmonth = "<?php echo $selected_month; ?>";
    var Pday = <?php echo $selected_day; ?>;
    var Pdate = "<?php echo $selected_date; ?>";
    $.ajax({
        type: "POST",
        url: 'mark_present.php',
        data: { id : Pid, year : Pyear, month : Pmonth, day : Pday, date : Pdate },
        dataType: "JSON",
        success: function(data){
            $("#message").html(data);
            window.location.href = 'mark_attendance.php';
            //window.location.reload();
        },
        error: function() {
            alert("Failure");
        }
    });
}

mark_present.php:

<?php 
include "db.php";
    $student_id = $_POST['id'];
    $year = $_POST['year'];
    $month = $_POST['month'];
    $day = $_POST['day'];
    $date = $_POST['date'];

    $sql = "INSERT INTO `student_attendance` SET student_id = '$student_id', year = '$year', month = '$month', day = '$day', date = '$date', status = '1' ";
    $result = mysql_query($sql);

    if($result){
        return json_encode(array("message"=>true));
        //echo "success";
    }else{
        return json_encode(array("message"=>false));
        //echo "error";
    }
?>
<?php 
include "db.php";
$student_id = $_POST['id'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$date = $_POST['date'];

$sql = "INSERT INTO student_attendance(student_id,year,month,day,date,status) value('$student_id', '$year', '$month', '$day', '$date', '1') ";
$result = mysql_query($sql);
?>

錯誤是在您的插入查詢上。

var Pyear = "<?php echo $selected_year; ?>";
var Pmonth = "<?php echo $selected_month; ?>";
var Pday = "<?php echo $selected_day; ?>";
var Pdate = "<?php echo $selected_date; ?>";

您需要使用"來獲取php變量以javascript檢查鏈接

將您的PHP代碼更改為

<?php 
include "db.php";
$student_id = $_POST['id'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$date = $_POST['date'];

$sql = "INSERT INTO `student_attendance` SET student_id = '$student_id', year = '$year', month = '$month', day = '$day', date = '$date', status = '1' ";
$result = mysql_query($sql);
if(!$result){
    return json_encode(array("message"=>"There is some error".mysql_error());
} else {
    return json_encode(array("message"=>"Record inserted successfully"));
}
?>

並將您的成功功能更改為

.success : function (data){
    console.log(data);
 }
.error : function(data){
    console.log(data);
 }

您將在控制台或成功消息中得到錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM