开发者

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

I have a lot of text to insert into a MySQL table using PHP. Part of the text looks like this example:

Yes, this is 'great'!

To fill this into an SQL Statement, I need to escape the '.

I'm using an ereg-replace $text=mb_ereg_replace("'","\\'", $text); to make the following work:

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

Now I found out that there is also another text-style, where I have to save to MySQL something like this:

As you can see the \' world\' is a "disc"!

So I tried adding more mb_ereg_replace like this:

$text=mb_ereg_replace("'","\\'", $text);
$text=mb_ereg_replac开发者_StackOverflow社区e("\\","\\\\", $text);

But this does not work, I just get the error message: PHP Warning: mb_ereg_replace(): mbregex compile err: end pattern at escape in [...]

What causes this? I probably made some mistake, but can't find it!

Thank you for any kind of help.


Use mysql_real_escape_string to escape your strings.

$text = mysql_real_escape_string($text);

Or better, use PDO and parameterized queries.


There's a much better way, and you won't need to worry about escaping your strings ever again. Using prepared statements in mysqli or PDO will both make large queries (ones with many rows) run much faster, they are secure, you don't have to worry about (most types of) SQL injection and they are easy to learn. the strings will just be accepted as is into your database without the risk of breaking your code.

Here's an example with 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();

Basicallly, by binding the parameters before it goes in, it just accepts any string the way you create it, and there's no need to escape anything.'

Here's the same thing using PDO. This does essentially the same thing but has the advantage of both working with multiple different database types (such as for instance Oracle or PostgreSQL) and also lends itself to some nifty modification due to the classes associated.

    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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜