Bodhidarma
Bodhidarma

Reputation: 559

mysql_real_escape_string() is not escaping anything

  1. would I need to use real escape in both my INSERT and SELECT FROM statements?
  2. why the syntax I'm using in the following example isn't working (It's just one of the many ways I've tried)?

    //insert user input for word 1
    $sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
    VALUES('$Word1','$Word2','$Word3','$Word4','$Word5')",
    mysql_real_escape_string($Word1),
    mysql_real_escape_string($Word2),
    mysql_real_escape_string($Word3),
    mysql_real_escape_string($Word4),
    mysql_real_escape_string($Word5);
    if(!mysql_query($sql,$con))
    {
      die('Error: ' . mysql_error());
    }
    

Upvotes: 0

Views: 592

Answers (2)

Mike
Mike

Reputation: 21659

I highly recommend that you avoid escaping altogether, and move directly to prepared statements with mysqli::prepare, perhaps via PDO. It's ultimately simpler and safer:

$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);

$sql =
    'INSERT INTO mytable ' .
    '(Word1, Word2, Word3, Word4, Word5)' .
    'VALUES(?, ?, ?, ?, ?)';

$stmt = $dbh->prepare($sql);

$words = array('word1', 'word2', 'word3', 'word4', 'word5');
$stmt->execute($words);

$words = array('word6', 'word7', 'word8', 'word9', 'word10');
$stmt->execute($words);

Upvotes: 1

Patrick
Patrick

Reputation: 3172

It looks like you are trying to use sprintf(), to do so properly you need to reformat your code a little:

$sql = sprintf("INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($Word1),
mysql_real_escape_string($Word2),
mysql_real_escape_string($Word3),
mysql_real_escape_string($Word4),
mysql_real_escape_string($Word5)
);

Upvotes: 4

Related Questions