Saul Tigh
Saul Tigh

Reputation: 177

Why mysql_real_escape_string doesn't work on $_POST?

This code for example won't escape the string of the comment for the database:

   if ($_POST['comment']) {
    $comment = mysql_real_escape_string(htmlentities($_POST['comment_txt']));
    $comment_insert = mysql_query("UPDATE msgs SET msg='$comment' WHERE user='$username'")
    or die;
    }

but this one will:

 if ($_POST['comment']) {
    $comment_p = $_POST['comment_txt'];
    $comment = mysql_real_escape_string(htmlentities($comment_p));
    $comment_insert = mysql_query("UPDATE msgs SET msg='$comment' WHERE user='$username'")
    or die;
    }

Why? Why can't I just escape the $_POST value? Why do I have to define new $variable for $_POST to escape it? This is security vise. I will move to PDO at some point, but at the moment I'm stuck with old mysql API.

Upvotes: 0

Views: 1179

Answers (2)

Maha Dev
Maha Dev

Reputation: 3965

Try this, it might help you :

$comment = mysql_real_escape_string(htmlentities($_POST['comment_txt'], ENT_QUOTES, "UTF-8"));

See details from here : PHP $_POST doesn't take accents

Upvotes: 2

Andreas
Andreas

Reputation: 2837

That's just wrong. You don't have to put the value in the $_POST array into a variable before, it works directly on the $_POST value, too

Consider using mysqli or PDO instead of mysql though.

Upvotes: 0

Related Questions