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 my开发者_StackOverflow中文版sql_real_escape_string() to fix this? Thanks.
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.
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')";
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.
精彩评论