繁体   English   中英

在PHP中,如何在插入MySQL表之前转义字符串中的单引号?

[英]In PHP, how can I escape single quotes in my string before inserting into a MySQL table?

我有很多文本可以使用PHP插入MySQL表中。 文本的一部分类似于以下示例:

Yes, this is 'great'!

要将其填充到SQL语句中,我需要对'进行转义。

我正在使用ereg-replace $text=mb_ereg_replace("'","\\\\'", $text); 使以下工作:

$sql="insert into mytable (msg) values ('".$text."')";

现在,我发现还有另一种文本样式,必须在其中保存如下内容:

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和参数化查询。

有一种更好的方法,您无需担心再次逃脱字符串的麻烦。 mysqliPDO使用准备好的语句将使大型查询(具有多行的查询)运行得更快,它们是安全的,您不必担心(大多数类型的)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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM