nl2br() line break in PHP with example


nl2br() line break in PHP with example

The nl2br() line break in PHP is an inbuilt function provided by PHP. It breaks the line of paragraph elements in HTML if the paragraph contains newlines. In many cases, we see that if we insert a small paragraph or large paragraph in the MySQL database then it is inserted as a whole string.

But when we echo the value of the paragraph from the MySQL database using PHP then we can not see the paragraph exactly in the way it has been inserted line by line. In order to achieve this, the nl2br() function is used to fetch the value of the paragraph as same as it was inserted. So, I am going to explain the example in a step-by-step process.

Also read, PHP difference between two dates in years, months and days

Explanation of nl2br() Line break in PHP

Step 1:- Create the database in Mysql.


Step 2:- Create a table in the database as shown below.


DDL information of the table

CREATE TABLE line_break (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
message varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
updated_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Step 3:- Create a file with a .php extension in the root directory of your local server. In my case, the filename is paragraph.php.


Step 4:- Add the below code to paragraph.php as shown below

paragraph.php

<?php

//Connect the database

$servername='localhost';
$username="root";
$password="";
try
{
  $con=new PDO("mysql:host=$servername;dbname=test_db",$username,$password);
  $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  //echo 'connected';
}
catch(PDOException $e)
{
  echo '<br>'.$e->getMessage();
}

//Get the data from the user

if(isset($_POST['submit']))
{
  $message = $_POST['message'];

//Insert the data in mysql database table

$sql="INSERT INTO line_break(message) VALUES('$message')";
      $stmt=$con->prepare($sql);
      $stmt->execute();

  }

?>

<html>
<head>
<title>Line Break in PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style>
.container{
    width:40%;
    height:30%;
    padding:20px;
}
</style>

</head>
<body>
   <div class="container">
    <h3 align="center"><u>nl2br() line break in PHP</u></h3>
    <br/><br/>
    <form class="form-horizontal" action="#" method="post">
              <div class="form-group">
                <label class="control-label col-sm-2" for="email">Message:</label>
                    <div class="col-sm-10">
                      <textarea name="message" rows="5" class="form-control"></textarea>
                    </div>
               </div>
              <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-primary btn-sm" name="submit">Save</button>
                </div>
              </div>
    </form>
    <br>
    <h4>Output:-</h4>
    <p>

      <?php
//fetch data from the table

      $stmt1=$con->query("select * from line_break order by id asc");
      $stmt1->execute();
      $rows=$stmt1->fetchAll(PDO::FETCH_ASSOC);
      if(!$rows){
        echo 'No data found';
      }
      else{
        foreach($rows as $value){
          echo nl2br($value['message']);
        }
      }

      ?>
     
    </p>

</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>


Step 5:- Now, add the below code to insert the value of the paragraph in the table of the database.

<?php
//Insert the data in mysql database table

$sql="INSERT INTO line_break(message) VALUES('$message')";
      $stmt=$con->prepare($sql);
      $stmt->execute();

  }
?>


Step 6:- Open the browser and paste the below URL.

http://localhost/paragraph.php


Step 7:- Now enter the text in the paragraph and submit.

When I entered the text as shown below

nl2br() line break in PHP with example

Output:-

Bootstrap is a free CSS framework. Bootstrap 3 is the most stable version of Bootstrap

When I entered the text as shown below

nl2br() line break in PHP with example

Output:-

Bootstrap 4 is a newer version of Bootstrap;
with new components, a faster stylesheet,
and more responsiveness.

Conclusion:- I hope this tutorial will help you to understand the concept and use of the nl2br function. If there is any doubt then please leave a comment below


Leave a Comment