mysql_real_escape_string()不会转义任何内容

时间:2010-12-05 04:13:39

标签: php mysql mysql-real-escape-string

  1. 我需要在INSERT和SELECT FROM语句中使用真正的转义吗?
  2. 为什么我在以下示例中使用的语法不起作用(这只是我尝试过的众多方法之一)?

    //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 个答案:

答案 0 :(得分:4)

看起来您正在尝试使用sprintf(),要正确地执行此操作,您需要重新格式化代码:

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

答案 1 :(得分:1)

我强烈建议您完全避免转义,并使用prepared statements直接转到mysqli::prepare,也许通过PDO。它最终更简单,更安全:

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