Hello I am having a problem
I am sending a javascript variable to my php script and attemping to store that variable in mysql db but it just does not work.
Here is my code:
js:
<script type="text/javascript">
var myData = "Hello";
function AJAXAction () {
$.ajax({
url: 'test.php',
data: { myPhpData: myData },
success: function (response) {
alert (response);
}
});
}
AJAXAction();
</script>
PHP:
<?php
$link = mysqli_connect("localhost","root","","testt") or die("Error " . mysqli_error($link));
function goDoIt ($link) {
$why = $_GET['myPhpData'];
$sql = "INSERT INTO test_table (id) VALUES '$why'";
mysqli_query($link, $sql);
echo "booooom";
}
goDoIt ($link);
mysqli_close($link);
?>
The result alerts "boooom" but it does not store my $why variable in my table
-
2I smell SQL injection vulnerabilities.. Use prepared statements!lethal-guitar– lethal-guitar2014年04月02日 13:48:34 +00:00Commented Apr 2, 2014 at 13:48
-
And add error handling.jeroen– jeroen2014年04月02日 13:55:15 +00:00Commented Apr 2, 2014 at 13:55
3 Answers 3
Try it:
$why = $_GET['myPhpData'];
$sql = "INSERT INTO test_table (id) VALUES '$why'";
if(mysqli_query($link, $sql)){
echo "booooom";
}else{
echo "error";
}
Then you can get if the query is correct or not.
Sign up to request clarification or add additional context in comments.
Variable should be enclosed in {} plus you need to enclose it in ()
$sql = "INSERT INTO test_table (id) VALUES ('{$why}')";
answered Apr 2, 2014 at 13:46
Ankur Aggarwal
3,0915 gold badges34 silver badges57 bronze badges
2 Comments
Joe
Thank you for this answer, however I have never needed to do this before hand when inserting values into a table? why is this?
Ankur Aggarwal
@Joe I am not very sure why the other way around it was not working. there are several ways to evaluate the variable. You can concat the string also. stackoverflow.com/questions/16001001/…
$sql = "INSERT INTO test_table (id) VALUES ('".$why."');
you can also do this
answered Apr 2, 2014 at 13:54
Ferrakkem Bhuiyan
2,7932 gold badges25 silver badges39 bronze badges
1 Comment
lethal-guitar
Still vulnerable to SQL injection. What if I pass
'); DROP TABLE test_table; -- in $why?default