带格式化的Mysql字符串输入

时间:2012-04-27 02:11:08

标签: php mysql command-line formatting phpmyadmin

我是MySQL的初学者,我在表格中正确格式化单元格时遇到了一些麻烦。

我将数据类型设置为TEXT,因此单元格中有一些小段落有足够的空间,但我的问题是,如何使用撇号,引号,冒号和其他标点符号格式化段落我通过命令行(MAC)插入该单元格?

这是列值:

joke TEXT NOT NULL,

我想在表格中插入这个示例笑话:

Husband says: "When I'm gone you'll never find another man like me".
Wife replied: "What makes you think I'd want another man like you!"

如何将其写入命令行,以便显示确切的格式或至少接近。我的命令行条目如下所示:

INSERT INTO jokes
(date_submitted, source, joke_style, joke)
VALUES
(NOW(), 'www.example.com','Blonde', 'Joke would go here with (: ' ,) and so on.');

我是否用\'来逃避撇号?我如何处理标点符号的其余部分,以及如何存储换行符?

2 个答案:

答案 0 :(得分:3)

使用mysql_real_escape_string()或切换到PDO并使用PDO::prepare()和占位符。

示例:

$sth = $pdo->prepare('INSERT INTO jokes ... VALUES (NOW, :joke, ...)');
$sth->execute(array(':joke' => $joke));

如果您需要手动编写命令,则应将'转义为\',换行符为\n。有关如何在MySQL中转义字符串的更多详细信息,请参阅有关string literals的手册部分。

答案 1 :(得分:1)

继承人manual

的摘录

以下SELECT语句演示了引用和转义的工作原理:

mysql> SELECT 'hello', '"hello"', '""hello""', 'hel''lo', '\'hello';
+-------+---------+-----------+--------+--------+
| hello | "hello" | ""hello"" | hel'lo | 'hello |
+-------+---------+-----------+--------+--------+

mysql> SELECT "hello", "'hello'", "''hello''", "hel""lo", "\"hello";
+-------+---------+-----------+--------+--------+
| hello | 'hello' | ''hello'' | hel"lo | "hello |
+-------+---------+-----------+--------+--------+

mysql> SELECT 'This\nIs\nFour\nLines';
+--------------------+
| This
Is
Four
Lines |
+--------------------+

mysql> SELECT 'disappearing\ backslash';
+------------------------+
| disappearing backslash |
+------------------------+