Adding a line break in MySQL INSERT INTO text

后端 未结 10 2042
太阳男子
太阳男子 2020-12-07 22:07

Could someone tell me how to add a new line in a text that I enter in a MySql table?

I tried using the \'\\n\' in the line I entered with INSERT I

相关标签:
10条回答
  • 2020-12-07 22:14

    If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:

    INSERT INTO mytable (myfield) VALUES ('hi this is some text
    and this is a linefeed.
    and another');
    

    I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS() and CHAR() worked for me.

    INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));
    
    0 讨论(0)
  • 2020-12-07 22:19

    First of all, if you want it displayed on a PHP form, the medium is HTML and so a new line will be rendered with the <br /> tag. Check the source HTML of the page - you may possibly have the new line rendered just as a line break, in which case your problem is simply one of translating the text for output to a web browser.

    0 讨论(0)
  • 2020-12-07 22:19
    1. You have to replace \n with <br/> before inset into database.

      $data = str_replace("\n", "<br/>", $data);

      In this case in database table you will see <br/> instead of new line.

      e.g.

      First Line
      Second Line

      will look like:

      First Line<br/>Second Line

    2. Another way to view data with new line. First read data from database. And then replace \n with <br/> e.g. :

      echo $data;
      $data = str_replace("\n", "<br/>", $data);
      echo "<br/><br/>" . $data;

      output:

      First Line Second Line

      First Line
      Second Line


      You will find details about function str_replace() here: http://php.net/manual/en/function.str-replace.php

    0 讨论(0)
  • 2020-12-07 22:22

    In SQL or MySQL you can use the char or chr functions to enter in an ASCII 13 for carriage return line feed, the \n equivilent. But as @David M has stated, you are most likely looking to have the HTML show this break and a br is what will work.

    0 讨论(0)
  • 2020-12-07 22:23

    in an actual SQL query, you just add a newline

    INSERT INTO table (text) VALUES ('hi this is some text
    and this is a linefeed.
    and another');
    
    0 讨论(0)
  • 2020-12-07 22:23
    INSERT INTO test VALUES('a line\nanother line');
    

    \n just works fine here

    0 讨论(0)
提交回复
热议问题