我有一个php页面,可以将一些数据保存到我的数据库中。 它适用于所有带有特殊字符 (. , ?!) 的字符串,但不适用于撇号 (')。
这是我的 php:
$message = trim(strip_tags($_REQUEST['message']));
$safe_variable = mysqli::escape_string($message);
$i_sql = "INSERT INTO tableName ( id_user, username, message) VALUES ( '".$id_user."', '".$username."', '".$safe_variable."')";
$i_res = mssql_query($i_sql);
我尝试过有和没有这一行:
$safe_variable = mysqli::escape_string($message);
而且我已经读到我应该使用mysql_real_escape_string
但它不再受支持,我应该改用mysqli::escape_string
。
我在PHP中做错了什么,或者我应该使用什么来保存撇号?
注意:
$message
测试时I'm
。
escape_string()
不能用mysqli::escape_string($message)
静态调用
此外,mssql_query($i_sql);
在这里没有任何意义,因为看起来您正在使用 mysql 作为数据库。
代码可以像这样修复:
// This is the object that represent the connection to the db
$conn = new mysqli( 'localhost', 'user', 'password', 'db_name');
$message = trim(strip_tags($_REQUEST['message']));
$safe_variable = $conn->escape_string($message); // fixed here
$i_sql = "INSERT INTO tableName ( id_user, username, message) VALUES ( '".$id_user."', '".$username."', '".$safe_variable."')";
$i_res = $conn->query($i_sql); // fixed here
当然,以上假设您使用mysql作为数据库。
无论如何,我强烈建议使用预准备语句而不是转义字符串。