steven
steven

Reputation: 4875

Store real line break in db

I have a field called eol (type: varchar) in my mysql database.

I set it to default \r\n in PHPMyAdmin.

if i doing a SELECT using PDO i do not recieve a real line break.

If I var_dump my result like this:

var_dump(unpack('C*',$eol));

The result is:

array(4) { 
[1]=> int(92) 
[2]=> int(114) 
[3]=> int(92) 
[4]=> int(110) 
} 

which is in fact:

If I var_dump a real line break

var_dump(unpack('C*',"\r\n"));

The result is:

array(2) { 
[1]=> int(13) 
[2]=> int(10) 
} 

How do I store a real line break properly in mysql?

EDIT:

@all if i doing simple

var_dump("\r\n");

it will be shown like this:

string(2) "
"

which is nice but I cannot see the real chars!

Upvotes: 1

Views: 2960

Answers (2)

user1741851
user1741851

Reputation:

The problem is not with the way mySQL database stores these values. PHPMyAdmin is just a GUI tool. Hence whatever you enter are considered as individual characters.

A simple example is the ASCII. 0x0A represents line feed but if you enter that using PHPMyAdmin you will get those characters instead of line feed. This is similar to that. I have stored line feeds into mysql columns using queries without any trouble.

For example -

insert into `evaluation_answer_versions` (`evaluation_answers_answer_id`, `question_version_id`, `answer_text`, `score`, `hidden`) values (1, 1, "\r\nabc", 1, 'n');

works as expected.

Upvotes: 1

Daniel W.
Daniel W.

Reputation: 32350

You don't need pack, special characters do get parsed when using double quotes:

var_dump("\r\n"); // 2 bytes CR LF, not 4 byte '\r\n' literal

You should maybe use in MySQL a 2 byte binary field instead of varchar.

$dbh->query("INSERT INTO x SET eol = '\r\n'");

Inserting \r\n through phpMyAdmin, it will escape the characters to \\r\\n.

Upvotes: 3

Related Questions