-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>
3
  • 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. Commented Oct 31, 2018 at 12:24
  • I know I know :) This was just to unserstand where I went wrong, but I found it, thank you! Commented Oct 31, 2018 at 12:29
  • Possible duplicate of Access JavaScript variables value in php to store in mysql Commented Oct 31, 2018 at 12:39

2 Answers 2

1

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

Good Luck

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the reply sir. Could you suggest what $q should be set to then?
@JaunSamtin You can use PHP filter functions to solve sql injection problems.
@JaunSamtin Please set correct answer as Accepted Answer to others can use your question.
0

You are doing an intval:

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

That's why "Ballsack" turns to 0.

1 Comment

I see, thank you. I was unaware of the meaning of intval.. I get it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.