如何将引号插入数据库

时间:2016-03-04 14:31:48

标签: php mysql

我原来的问题:insert special characters

我想插入"""使用php进入数据库,我使用该函数来转义引号:

$text = str_replace("\"","\\\"",$text);

我原来的数据是:

"support.apple.com/kb/HT4070"

但是当我检查我的数据库时,它会显示:

\"support.apple.com/kb/HT4070\"

我想保留这个引用,我怎么能在php中做到这一点?非常感谢你。

3 个答案:

答案 0 :(得分:4)

永远不要直接这样做。您可以拥有SQL Injection attack

如果您使用PDO,请使用地方hodlders:

$stmt = $pdo->prepare('INSERT INTO texts (text) VALUES (?)');
$stmt->execute([$text]);

您也可以选择使用以下符号对引号和其他不良字符进行编码:

$text4db = htmlentities($text);

通过使用占位符,您可以直接将引用的字符串保存到数据库中,并在保存它们时稍后检索它。

例如:

$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"'

答案 1 :(得分:0)

对于MySQL中的过滤器,请使用mysql_escape_string。

以这种方式使用。

$ text = mysql_real_escape_string($ text);

但是在新版本的PHP中不推荐使用此函数。如果您使用新版本的PHP阅读本文。 http://php.net/manual/en/function.mysql-escape-string.php

答案 2 :(得分:0)

我找到的正确方法是:

$text = str_replace("\\","\\\\",$text);   // this code changes \ to \\
$text = str_replace("\\\"", "\"",$text);  // this code changes  \" to "
相关问题