将Javascript信息发送到php并保存在数据库中

Send Javascript info to php and save it on a database

本文关键字:保存 存在 数据库 php Javascript 信息      更新时间:2023-09-26

一位前同事开发了一个将结果发送到数据库的测验。他被解雇了,但我需要再次使用那个密码。我只有javascript代码,我需要重新创建php (save.php),从javascript保存信息。你能帮我的php代码或给我一个提示。Thaks !

    $(document).ready(function() {
    $("#answer_a").click(function() { 
    $.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "a" } );
}); 
    $("#answer_b").click(function() { 
    $.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "b" } ); 
});
    $("#answer_c").click(function() { 
    $.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "c" } ); 
});
    $("#answer_d").click(function() { 
    $.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "d" } ); 
});

    });

在save.php中使用$_GET[]来使用变量并将它们保存在您的表中

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$test = mysqli_real_escape_string($con, $_GET['test']);
$question = mysqli_real_escape_string($con, $_GET['question']);
$answer = mysqli_real_escape_string($con, $_GET['answer']);
$sql="INSERT INTO Persons (test, question, answer)
VALUES ('$test', '$question', '$answer')";
if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

使用$_GET[<name>]获取php中的值,使用mysqli_connect将数据插入表

您已经在正确的轨道上,下一步是在PHP中。您可以使用这个示例来获取这些值。考虑这个例子:

<?php
if(isset($_GET['test'])) {
    $data = array(); // initialize return data holder
    $test = isset($_GET['test']) ? $_GET['test'] : null;
    $question = isset($_GET['question']) ? $_GET['question'] : null;
    $answer = isset($_GET['answer']) ? $_GET['answer'] : null;
    // they should be inside now, now you can go on with mysql inserts
    // just a sample callback value to check if indeed php got it
    $data['test'] = $test;
    $data['question'] = $question;
    $data['answer'] = $test;
    echo json_encode($data);
    exit;
}

?>
<!-- lets say this is an image -->
<button id="answerswer_a" type="button">Hi im an image</button>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#answer_a").click(function() { 
        $.get("index.php", {test: "1", question: "1", answer: "a" }, function(response){
            var data = $.parseJSON(response);
            console.log(data); // check this in console
        });
    }); 
});
</script>