简体   繁体   中英

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

I know this question gets asked a lot, but I went through all the similar questions on here and I still can't fix my script. The Insert query works, but the "Name" shows up as 0 in the database. My 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>

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

It is because of $q = intval($_GET['q']); .
It change your string to 0. See PHP intval

Good Luck

You are doing an intval:

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

That's why "Ballsack" turns to 0.

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