0

I am trying to send two variables to my PHP file to insert them into a database. One variable is called 'skuLabel', which is just text and the other is 'jsonString', which is a JSON representation of a canvas design. When I just try to send the 'skuLabel', it works fine and inserts it like I would expect. But, when I send either just the 'jsonString' or both, my PHP errors that the two indexes do not exist when I try to access them. I've been working on this for several days now, trying many different methods, all with the same result. This is my first attempt at using AJAX, so I am sure I am doing something simple wrong. I appreciate any help anyone can give!

Here is my code:

var skuLabel = document.getElementById('sku').value;
var jsonString = JSON.stringify(canvas.toDatalessJSON());
$.ajax({
    type:   'POST',
    url:    'uploadDesign.php', 
    dataType: 'json',
    data:   {sku: skuLabel, json: jsonString},
    success: 
            function(data){
                alert(data);
            }
});

And PHP:

$sku = $_POST['sku'];
$jsonData = $_POST['json'];
if($mysqli->query("INSERT INTO designs (sku, jsonData) VALUES($sku, $jsonData)")===TRUE){
    printf("Inserted successfully.\n");
}
dheavjr
  • 21
  • 1
  • 5
  • 5
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Dec 22 '14 at 16:36
  • The basic problem here is that you aren't properly quoting and escaping your variables because smashing them into the string of SQL. This also opens you up to SQL injection. The solution is the same as that for protecting yourself from SQL injection. – Quentin Dec 22 '14 at 16:37
  • Thanks for the information, Quentin! I guess I was more focused on getting the AJAX code to send the variables than I was for security...Should have known better. – dheavjr Dec 22 '14 at 16:43
  • But would SQL injection vulnerability cause the data to not be passed at all? i.e. var_dump(_$POST); returns array(0){} – dheavjr Dec 22 '14 at 16:49
  • No, it wouldn't. It would definitely cause the SQL query to fail if you shoved JSON in one of the variables, but there is no obvious cause for the code you've provided to not send the data at all. – Quentin Dec 22 '14 at 16:50
  • Ok, thanks again for the information. I'll be sure to at least fix that issue. – dheavjr Dec 22 '14 at 16:57

1 Answers1

0
if($stmt = $mysqli->prepare("INSERT INTO designs (sku, jsonData) VALUES(?, ?)")){
    $stmt->bind_param('ss', $sku, $jsonData);
    $stmt->execute();
    $stmt->close();
}

This fixed it. Thanks, Quentin!

dheavjr
  • 21
  • 1
  • 5