我有很多文本插入到MySQL表使用PHP。部分文本看起来像这个例子:
Yes, this is 'great'!
要将其填充到SQL语句中,我需要转义'
.
我使用一个ereg-replace $text=mb_ereg_replace("'","'''", $text);
使以下工作:
$sql="insert into mytable (msg) values ('".$text."')";
现在我发现还有另一种文本样式,我必须像这样保存到MySQL:
As you can see the '' world'' is a "disc"!
所以我试着添加更多的mb_ereg_replace,像这样:
$text=mb_ereg_replace("'","'''", $text);
$text=mb_ereg_replace("''","''''", $text);
但这不起作用,我只是得到错误信息:PHP Warning: mb_ereg_replace(): mbregex compile err: end pattern at escape in [...]
是什么原因造成的?我可能犯了什么错误,但是找不到!
谢谢你的帮助。
使用mysql_real_escape_string
转义字符串。
$text = mysql_real_escape_string($text);
或者更好,使用PDO和参数化查询
有一个更好的方法,您再也不用担心转义字符串了。在mysqli
或PDO
中使用准备好的语句将使大型查询(有许多行的查询)运行得更快,它们是安全的,你不必担心(大多数类型)SQL注入,而且它们很容易学习。字符串将被接受为数据库,没有破坏代码的风险。
以下是mysqli
的示例:
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO table (columnname) VALUES (?)");
$stmt->bind_param("s", $text);
$stmt->execute();
$stmt->close();
基本上,通过在它进入之前绑定参数,它只接受你创建的任何字符串,不需要转义任何东西。
这里使用PDO也是同样的事情。这在本质上做同样的事情,但有一个优点,即可以处理多种不同的数据库类型(例如Oracle或PostgreSQL),并且由于相关的类,也可以进行一些漂亮的修改。
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO table (columname)
VALUES (:text)");
$stmt->bindParam(':text', $text);
$stmt->execute();
catch(PDOException $e)
{
echo "Oops, didn't work: " . $e->getMessage();
}
$conn = null;