mysql_real_escape_string() is not escaping anything

旧街凉风 提交于 2020-01-16 14:39:14

问题


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

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



回答2:


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


来源:https://stackoverflow.com/questions/4357340/mysql-real-escape-string-is-not-escaping-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!