简体   繁体   English

如何在 MySQL 选择中转义单引号和双引号?

[英]How to escape single & double quotes in MySQL select?

select name from movies where id = 1; gives me给我

name
----------
How the 'A' Stole Christmas

How would I select in order to get我将如何选择才能获得

name
----------
How the \'A\' Stole Christmas

I can use replace(title,'\\'','\\\\\\'') which turns ugly since I need to do it twice one for single & double quote, Curious to know if there is cleaner approach我可以使用replace(title,'\\'','\\\\\\'')这变得丑陋,因为我需要为单引号和双引号做两次,想知道是否有更清洁的方法

Struggling with escaping characters is a sign that you may be unnecessarily converting strings manually as data flows through different systems.挣扎于转义字符表明您可能会在数据流经不同系统时不必要地手动转换字符串。 The question I would ask is whether it is necessary to have escaped strings for your requirements.我要问的问题是是否有必要根据您的要求转义字符串。

When constructing and executing your queries you should use bind variables which removes the need to quote strings to build up your Sql queries and minimizes the risk of Sql injection security issues.在构建和执行查询时,您应该使用绑定变量,这样就无需引用字符串来构建 Sql 查询,并最大限度地降低 Sql 注入安全问题的风险。

See http://php.net/manual/en/mysqli-stmt.bind-param.phphttp://php.net/manual/en/mysqli-stmt.bind-param.php

Once you have Sql results in a variable or PHP structure it is often better to find functions/libraries such as JSON functions described at https://coderwall.com/p/p2kumg/json_encode-vs-serialize-with-php-arrays一旦您在变量或 PHP 结构中获得 Sql 结果,通常最好找到函数/库,例如https://coderwall.com/p/p2kumg/json_encode-vs-serialize-with-php-arrays 中描述的 JSON 函数

And of course there's http://www.w3schools.com/php/func_string_addslashes.asp as mentioned by D4V1D as a comment.当然还有 D4V1D 作为评论提到的http://www.w3schools.com/php/func_string_addslashes.asp

Edit ... There also appears to be a Mysql QUOTE() function that does what you are asking.编辑...似乎还有一个 Mysql QUOTE() 函数可以满足您的要求。

See http://www.w3resource.com/mysql/string-functions/mysql-quote-function.phphttp://www.w3resource.com/mysql/string-functions/mysql-quote-function.php

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

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