如何将报价插入数据库 [英] How to insert Quotes into database
问题描述
我原来的问题:插入特殊字符
我想用php将"""插入到数据库中,我用函数来转义引号:
I want to insert the """ into database with php, and I use the function to escape the quotes:
$text = str_replace("\"","\\\"",$text);
我的原始数据是:
"support.apple.com/kb/HT4070"
但是当我检查我的数据库时它显示:
but when I check my database it shows:
\"support.apple.com/kb/HT4070\"
我想保留这句话,我怎么能在php中做到这一点?非常感谢.
and I want to keep this quote, how can I do it in the php? Thank you very much.
推荐答案
切勿直接执行此操作.您可能会遇到 SQL 注入攻击
Never do this directly. You can have a SQL Injection attack
如果您使用 PDO,请使用 place hodlders:
If you use PDO, use place hodlders:
$stmt = $pdo->prepare('INSERT INTO texts (text) VALUES (?)');
$stmt->execute([$text]);
或者,您还可以使用以下代码对引号和其他坏字符进行编码:
Optionally you can also encode the quotes and other bad characters with:
$text4db = htmlentities($text);
通过使用占位符,您可以直接将引用的字符串保存到数据库中,并在保存时检索它.
By using placeholders you can directly save quoted strings to the database and retrieve it later as you saved them.
例如:
$text = 'My "text" has "quotes"';
$stmt = $pdo->prepare('INSERT INTO texts (text) VALUES (?)');
$stmt->execute([$text]);
// later
$stmt = $pdo->prepare('SELECT text FROM texts LIMIT 1');
$stmt->execute([$text]);
$text = $stmt->fetchColumn();
// now $text has the same text: 'My "text" has "quotes"'
这篇关于如何将报价插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!