Thomas van Beek
Thomas van Beek

Reputation: 3

Syntax Error MySQL from Ajax GET

I'm having a weird issue for the last couple of weeks that I just can't figure out.

I have a textarea that's triggered on a KeyUp to push it's contents to a insert page through jQuery Ajax like so:

$('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);
        });
});

On the dbUpdate.inc.php I do this:

<?php
$value = mysql_real_escape_string($_GET['val']);

$query = "UPDATE table SET column = '".$value."' WHERE a = ".$b;
mysql_query($query) or die(mysql_error());
?>

It all works perfect like it should, all text gets update in the right column in the right row. It only keeps throwing a syntax error when I have a single quotation mark ('), which should be escaped by mysql_real_escape_string (Addslashes doesn't work either). Am I missing something or is there any weird behaviour I should be looking for?

Code isn't actual production code, but simplified for this post.

Upvotes: 0

Views: 94

Answers (3)

Ian Droogmans
Ian Droogmans

Reputation: 75

I advise you to use PDO, specifically the prepare statement.

$sql = 'UPDATE table SET column = :value WHERE a = ".$b';
$sth = $dbh->prepare($sql);
$sth->execute(array(':value' => $_GET['value']));

Find more info on pdo and the prepare statement. http://www.php.net/manual/en/pdo.prepare.php

Upvotes: 0

GautamD31
GautamD31

Reputation: 28753

Better to add addslashes

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

Then you can go for the escape string

mysql_real_escape_string($value);

Keep in mind that mysql_* functions are deprecated so better you use mysqli_* functions or PDO statements.

Upvotes: 2

Su4p
Su4p

Reputation: 865

mysql_query is deprecated with mysqli or PDO you won't bother with this kind of issue.

Upvotes: 2

Related Questions