开发者

Escaping values with apostrophes for MySQL insert

I am trying to create some SQL insert statements and a few variables have names like the following:

  • "Aamma's Pastries"

I wa开发者_如何学Gont to escape the quote (') as I am adding the value into the MySQL database. How do I do that with PHP?


You've already accepted an answer, but I'd like to suggest a better approach to you. Using an approach like mysql_real_escape_string requires you to consistently remember to apply it every single time in every single query; it's tedious and error prone.

A more simple approach, which also ensures consistency is to use parameterised statements. This ensures that everything is correctly escaped, and also avoids you having to embed variables in your queries.

In PHP, this can be used with the newer PDO or MySQLi libraries. Of these, I prefer PDO for the flexibility it provides (e.g. I'm currently stuck with MySQL, but I don't intend to keep my app running that way forever, and with PDO the migration will be massively simplified), but there are plenty of questions here on SO that cover the pros and cons of each.


Have a look at mysql_real_escape_string


Please use prepare statements and let mysql handle escaping itself and you doing at code level


There is this function that you can use that escapes all characters that you need, here is a code example in php

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜