fealiuex
fealiuex

Reputation: 9

mysql_real_escape_string() to allow ' and "

I'm making a new question seeing as the other question is inactive and it has changed very much. My db code is this:

$sql2="INSERT INTO $tbl_name(s_id, s_name, s_email, s_content)VALUES('$id', '$s_name', '$s_email', '$s_content')";
$result2=mysql_query($sql2);

if($result2){
echo "Successful<BR>";

}
else {
echo "ERROR";
}

I can input letters numbers, but not ' or " - how can I use mysql_real_escape_string() to fix this? Thanks.

Upvotes: 0

Views: 469

Answers (3)

Emre Yazici
Emre Yazici

Reputation: 10174

You should escape your string variable inside or outside your query with mysql_real_escape_string:

$name    = mysql_real_escape_string($s_name);
$email   = mysql_real_escape_string($s_email);
$content = mysql_real_escape_string($s_content);

$sql2 = "INSERT INTO $tbl_name(`s_id`, `s_name`, `s_email`, `s_content`) \n";
$sql2.= "VALUES('$id', '$name', '$email', '$content')";

Upvotes: 0

Bailey Parker
Bailey Parker

Reputation: 15905

mysql_real_escape_string() doesn't prevent you from using characters like ' or " that could possibly facilitate a SQL Injection. It simply escapes these characters so MySQL interprets them as their literal value and not as a command in the query. So you answer is, just use it. You don't have to do anything else.

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

Just use mysql_real_escape_string() to escape your strings before injecting them into your SQL query.

For example :

$s_name_escaped = mysql_real_escape_string($s_name);
$s_email_escaped = mysql_real_escape_string($s_email);
$s_content_escaped = mysql_real_escape_string($s_content);

$sql2="INSERT INTO $tbl_name(s_id, s_name, s_email, s_content)
       VALUES('$id', '$s_name_escaped', '$s_email_escaped', '$s_content_escaped')";


Or, maybe even better : stop using the old mysql_* functions, and use either mysqli_* or PDO, with Prepared statements.

Upvotes: 5

Related Questions