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

Joe
  • 267
  • 1
  • 6
  • 17

3 Answers3

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.

Amauri
  • 179
  • 3
  • 11
  • 1
    I'd upvote for the error handling, but the obvious sql injection kind of ruins the answer. – jeroen Apr 02 '14 at 13:57
  • Sure, you can add some function that prevents SQL Injection, I just wanted to show a way to cath the error – Amauri Apr 02 '14 at 14:58
1

Variable should be enclosed in {} plus you need to enclose it in ()

  $sql = "INSERT INTO test_table (id) VALUES ('{$why}')";
Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56
  • 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 Apr 02 '14 at 13:47
  • @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. http://stackoverflow.com/questions/16001001/selecting-mysql-query-via-php-variables – Ankur Aggarwal Apr 02 '14 at 13:56
1
$sql = "INSERT INTO test_table (id) VALUES ('".$why."');

you can also do this

Ferrakkem Bhuiyan
  • 2,741
  • 2
  • 22
  • 38