0

I'm sending a AJAX Call to a seperate file for a MySQL INSERT query. Everything works perfect until someone uses a quote ('); MySQL throws a syntax error even though before the query I use addslashes and mysqli_real_escape_string. This problem occurs in Safari but doesn't in Chrome.

Anyone know more about this specific issue and how to fix it?

jQuery Ajax

 $('body').on('keyup', '.dbDriven', function() {
        var val = $(this).val();

        $.ajax({url: 'dbUpdate.inc.php',type: "GET",data:
            {
                val: val
            }
        }).done(function ( data ) {
                        console.log(data);
        });
    });

dbUpdate.inc.php

$_GET['val'] = addslashes($_GET['val']);
$value = mysqli_real_escape_string($_GET['val']);

mysqli_query("UPDATE table SET column = `".$value."` WHERE id = '1'") or die(mysql_error());
  • 1
    You should consider learning about SQL injection. Data should not be going to the DB raw :/ – Benjamin Gruenbaum Apr 04 '14 at 16:04
  • `addslashes` is really not the right tool for the job, `mysqli_real_escape_string` is suboptimal and it sounds like you aren't using it correctly. – Quentin Apr 04 '14 at 16:05
  • 1
    Read about [SQL injection attacks](http://bobby-tables.com/) and how to use a modern API to[defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) against them. – Quentin Apr 04 '14 at 16:06
  • For the record, if you don't show the specific code that you're using, you're unlikely to get a specific answer. – Patrick Q Apr 04 '14 at 16:09

3 Answers3

0

Is more easily pass the variable through the url, this work only with "GET" method

$('body').on('keyup', '.dbDriven', function() {
    var val = $(this).val();

    $.ajax({url: 'dbUpdate.inc.php?val='+val,type: "GET"

    }).done(function ( data ) {
                    console.log(data);
    });
});
clairerb6
  • 99
  • 8
0

never use " " in javascript, it is a bad practice if you want you can directly make the POST or GET call like this :

      $.post(URL,data,callback);

or

      $.get(URL,data,callback);

or with you way :

       $.ajax({
            url: 'yoururl',
            type:'POST',           
            success: function(){                
        }});

Regards

cyril
  • 872
  • 6
  • 29
-4

Use this code to prevent SQLi:

$str = stripslashes(strip_tags(@trim(str_replace("'", "", $str))));
Mombay
  • 55
  • 7