0

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

asked Apr 2, 2014 at 13:43
2
  • 2
    I smell SQL injection vulnerabilities.. Use prepared statements! Commented Apr 2, 2014 at 13:48
  • And add error handling. Commented Apr 2, 2014 at 13:55

3 Answers 3

2

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.

answered Apr 2, 2014 at 13:50
Sign up to request clarification or add additional context in comments.

2 Comments

I'd upvote for the error handling, but the obvious sql injection kind of ruins the answer.
Sure, you can add some function that prevents SQL Injection, I just wanted to show a way to cath the error
1

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

2 Comments

Thank you for this answer, however I have never needed to do this before hand when inserting values into a table? why is this?
@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/…
1
$sql = "INSERT INTO test_table (id) VALUES ('".$why."');

you can also do this

answered Apr 2, 2014 at 13:54

1 Comment

Still vulnerable to SQL injection. What if I pass '); DROP TABLE test_table; -- in $why?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.