MySQL_real_escape_string not adding slashes?

2019-08-09 23:01发布

问题:

So I do this:

   <?php
    session_start();
    include("../loginconnect.php");
mysql_real_escape_string($_POST[int]);
    $int = nl2br($_POST[int]);
    $query = "UPDATE `DB`.`TABLE` SET `interests`='$int' WHERE `user`='$_SESSION[user]'";
    mysql_query($query) or die(mysql_error());
    mysql_close($con);
    ?>

And let's say that $_POST[int] is "Foo' bar." The single-quote remains unescaped AND I get a MySQL error when running the script, due to the quote. What's wrong?

回答1:

m_r_e_s() RETURNS the escaped value, it doesn't modify the original.

$int = mysql_real_escape_string($_POST['int']);

$query = "UPDATE ... interests = '$int' ...";

Note that I've added quotes around the int in the POST value. Without the quotes, PHP sees it as a constant value (e.g. define()). If it doesn't find a constant of that name, it politely assumes you meant it to be used a string and adjust accordingly, but issues a warning. If you had done

define('int', 'some totally wonky value');

previously, then you'd be accessing the wrong POST value, because PHP would see it as $_POST[some totally wonky value] instead.



回答2:

You're not using the results of mysql_real_escape_string in your query. Try doing this:

$int = nl2br(mysql_real_escape_string($_POST[int]););


回答3:

  • You should be using prepared statements. It has a slight learning curve over mysql_* functions, but is well worth it in the long run.
  • You should quote your strings, like $_POST['int'] instead of $_POST[int].
  • At the top of your file put error_reporting(-1);