Search code examples
phpmysqlflashmysql-real-escape-stringinsert-into

(PHP/MYSQL) mysql_real_escape_string not working


Recently, I've been having a problem with INSERT INTO not working properly when inserting certain strings. I discovered that the cause was the string contained apostrophes which were messing with my code. To solve this, I've been trying to use mysql_real_escape_string(), but it won't do anything. I read that it's supposed to insert \ before every "dangerous" special character, but when I echo'd the result of mysql_real_escape_string() it shows me the same string before and after, no \ s. How do I fix this? Here's my code...

<?php 

include "connect.php";  //connect.php connects to the database.

mysql_real_escape_string($_POST['username']);
mysql_real_escape_string($_POST['password']);
mysql_real_escape_string($_POST['sdNamer']);
mysql_real_escape_string($_POST['sdTrunk']);
//$_POST['username'] and the rest is the data entered by the user. 
$username = $_POST['username'];
$password = $_POST['password'];
$sdName = $_POST['sdNamer'];
$sdTrunkest = $_POST['sdTrunk'];

$sql = "INSERT INTO users (username, password, user_bio, starterDeck, Trunk) VALUES ('$username', '$password', 'User', '$sdName', '$sdTrunkest')";
//INSERT INTO won't work, because $sdTrunkest has string that contains an apostrophe, and mysql_real_escape_string isn't doing anything about it.
mysql_query($sql); 
exit("result_message=Success");
?>

Solution

  • mysql_real_escape_string() returns the modified string, but you're not doing anything with that string. You're essentially not using mysql_real_escape_string(). Use the returned value instead of the original unmodified value:

    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    // etc...
    

    Also, as a side note, there are two more serious problems with your code:

    1. Don't use mysql_* functions anymore. Update your code. (Read the introduction here to get started.)
    2. You're storing passwords in plain next. Never store passwords in plain text.