繁体   English   中英

如何使用 AJAX 和 PHP 将 JavaScript 变量发布到 MySQL 数据库中?

[英]How to post a JavaScript variable into a MySQL database using AJAX and PHP?

我知道这个问题经常被问到,但我在这里解决了所有类似的问题,但我仍然无法修复我的脚本。 插入查询有效,但“名称”在数据库中显示为 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>

这是因为$q = intval($_GET['q']); .
它将您的字符串更改为 0。请参阅PHP intval

祝你好运

你正在做一个intval:

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

这就是“Ballsack”变成0的原因。

暂无
暂无

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

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