如何使用ajax和php将javascript变量发布到mysql数据库中?

bq9c1y66  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我知道这个问题被问了很多,但我在这里经历了所有类似的问题,我仍然无法修复我的脚本。insert查询可以工作,但“name”在数据库中显示为0。我的javascript:

<html>
<head>
<script>
function SendData() 
{
var Name = "Ballsack"; //The name I am trying to get into database.
        if (window.XMLHttpRequest) 
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } 
        else 
        {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET","getuser.php?q="+Name,true);
        xmlhttp.send();
        alert("The query was send");

}
</script>
</head>
<body>

<form>
<input type="button" value="Send" onClick="SendData();"><br>
</form>

</body>
</html>

我的php(getuser.php):

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','jack','*****','VLA');
if (!$con) 
{
    die('Could not connect: ' . mysqli_error($con));
}

$query = "INSERT INTO TrafficRegisterDetails
(Name,Surname,Age,Address,TrafficRegNumb,NumberPlate)
VALUES('$q','Sak','12','Kernma','1212','blahblah')";
$result = $con->query($query);
if (!$result) die ("Database access failed: ".$con->error);

mysqli_close($con);
?>
</body>
</html>
0md85ypi

0md85ypi1#

这是因为 $q = intval($_GET['q']); .
它会将字符串更改为0。请参阅php intval
祝你好运

mwecs4sa

mwecs4sa2#

您正在执行intval:

$q = intval($_GET['q']);

这就是为什么“ballsack”变成0。

相关问题