-2

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>
  • 2
    First fix your security issue for sql injection. Then you don't need html code in your getuser.php file. Are those file on the same server ? maybe you should have a look at CORS and headers to make an API. Then why parsing the name you are sending as int ? Read php manual to get some informations about what are the functions you are using doing. – Zyigh Oct 31 '18 at 12:24
  • I know I know :) This was just to unserstand where I went wrong, but I found it, thank you! – Jaun Samtin Oct 31 '18 at 12:29
  • Possible duplicate of [Access JavaScript variables value in php to store in mysql](https://stackoverflow.com/questions/16806126/access-javascript-variables-value-in-php-to-store-in-mysql) – El.Hum Oct 31 '18 at 12:39

2 Answers2

1

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

Good Luck

0

You are doing an intval:

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

That's why "Ballsack" turns to 0.

José Carlos PHP
  • 1,417
  • 1
  • 13
  • 20