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

2 Answers 2

4

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)
);
Sign up to request clarification or add additional context in comments.

2 Comments

what is the significance of %s?
it's a data type specifer for php formatting strings, if you go to php.net/sprintf it will detail the various type specifiers available
1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.