How to use line break in the PHP variable that will be stored in a database table?

Asked

Viewed 6,535 times

0

My question is the following, I have a field in a MYSQL table that stores data and this data is displayed to the user.

This data is entered by users, however, users can also add information in this table field and this information is concatenated with the old ones (i.e., the value is not replaced).

Only when it is displayed it is kind of bizarre everything in one row. See the table and the view in html.

inserir a descrição da imagem aqui

Output on Page

inserir a descrição da imagem aqui

Just to be clear, I first inserted Flamengo, then Vasco, then Botafogo, then Palmeiras and finally Santos.

Only I would like every time I add data in this field, the items are displayed on the HTML page breaking line. That is, Each club stayed in one line.

I’ve been able to make room for information, but the break in line is breaking me.

If you can help me, I’d be grateful.

I used AJAX to send the data and PHP to query the Mysql database.

I don’t think we need to add the code to that question.

I hope I’ve been as clear as possible. Thank you!

I entered the Code to better detail the situation.

<div class="modal" tabindex="-1" id="modal-observacoes">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-success">
        <button class="close" aria-label="close" data-dismiss="modal">
                                    <span aria-hidden="true">&times;</span>
                                </button>
        <h4 class="modal-title">Inserir Observações na Atividade</h4>
      </div>

      <div class="modal-body bg-success">

        <form id="inserir-observacoes">

          <div class="form-group col-lg-12" style="font-size: 120%">
            <label for="observacoes-modal">Observações - Máximo de 500 caracteres</label>
            <textarea class="form-control" name="observacoes-modal" id="observacoes-modal" style="resize: none" rows="4" maxlength="500" required></textarea>
          </div>

          <input type="text" name="codigo-modal-observacoes" id="codigo-modal-observacoes">
          <input type="submit" class="btn btn-primary" name="enviar-modal-observacoes" id="enviar-modal-observacoes" value="Inserir">


        </form>

        <!--
                                <div id="confirmacao-inserir-informacoes">
                                    
                                    <h4></h4>
                                    
                                </div>
                                -->


      </div>

    </div>
  </div>
</div>


<!-- PARTE PHP QUE FAZ REALIZA O RECEBIMENTO DOS DADOS E EXECUTA A QUERY -->
<?PHP

 if($_POST)
        {
                        
            
            //PREENCHE AS VARIÁVEIS COM OS DADOS VINDOS DOS CAMPOS DO FORMULÁRIO
            $observacoes = !empty($_POST["observacoes-modal"]) ? " \n" . $_POST["observacoes-modal"] : null;
            $codigo  = !empty($_POST["codigo-modal-observacoes"]) ? $_POST["codigo-modal-observacoes"] : null;
            
            
            
            $pesquisar_observacoes = "UPDATE tbl_atividades SET DETALHES = CONCAT(DETALHES, '$observacoes'), DATA_DETALHES = NOW(), DETALHE_VISUALIZADO = '$resultado' WHERE codigo = $codigo"; 
            $operacao_insercao_observacoes = mysqli_query($conecta, $pesquisar_observacoes) or die("Erro no Update");   
            
     }
     
?>

I WAS ABLE TO FIX IT WITH SAM’S ANSWER. I ADDED A
CONCATENATED WITH THE TEXT COMING FROM THE FORM IN THE PHP VARIABLE ENTERING THE UPDATE QUERY.

But now I’m faced with another problem. When the column has the value 'null' in the database, I cannot concatenate with the value coming from the form.

  • 1

    An idea would be to add after each team name a "_", guy: Flamengo_Vasco_Botafogo_Atlético Mineiro_, and in PHP replace "_" by a <br>.

  • I think adding the code is necessary. Where are you getting input from? Is it from a textarea? from a WYSIWYG? The strings contain something like \n while in Javascript?

  • In place of space you substitute for <br>, example: echo str_replace(' ', '<br>', $valor_banco); .

  • 1

    You used a textarea to enter this information? Because if so, when the user presses the enter generates the \n automatically. Then, in php, you can use nl2br or the str_replace and insert the <br> in the text. When you make the selection will already be there!

  • @Lipespry I just don’t know if it’s really that! = ) But if you have an answer in mind about that, you can do!

  • @Lipespry who said that his comment responds, that is defined by the author of the question!

  • 1

    @Lipespry yes, but, that is the author of the question decides, he could get into the comment and say that is the answer, but, your assumption may be wrong and then you know that life here is not easy, I’m just warning and sorry for that.

  • 1

    The problem, in my view, is that there are many solutions to this answer. To get to something closer would be nice to know how the data is added. In this case, Flamento and Vasco are together!

  • 1

    And actually @Andreicoelho is a bad option as it adds.

  • 2

    @Andreicoelho Do replace by space will not work because if the team has more than one word (ex. Atlético Mineiro) will insert a <br> in the middle of the team name: Atlético<br>Mineiro

  • truth @Sam ... Why I think to get into something closer would be better to see how the die is entered! That’s where I mean! And looking at what you have said now, I believe that no regex or replace will result in a solution in the way the data is. It is necessary to change the way it is inserted... In my view...

  • 1

    He could already bench the <br>, guy: Flamengo<br>Vasco<br>Botafogo etc., but I suggested putting a _ in place of <br> because it saves space in the bank: Flamengo_Vasco_Botafogo etc.... then just do the replace: str_replace('_', '<br>', $valor_banco);

  • @Sam exact! That was the solution I referred to in the first comment! He already put in the bank the <br> of life!

  • 1

    @Lipespry I know the purpose of the site, but that being an assumption is not an answer, that’s what I’m saying. Comment is not answer even below has happened other questions that I agree, if the question guy says nothing is complicated to know what he needs. In fact the information could not be recorded like this.

Show 9 more comments

1 answer

8


"- Only I would like every time I add data in this field, the items are displayed on the HTML page breaking line. That is, Each club stayed in one line."

One of the many alternatives, which I thought was quite simple, is to add a line break at each value added in your database. And when showing, already in PHP, use the function nl2br.

To facilitate reproduction, I will use a string part by part - that symbolizes you inserting the parts one by one in your database:

<?php
$str = 'Flamengo'.PHP_EOL;
$str .= 'Vasco'.PHP_EOL;
$str .= 'Botafogo'.PHP_EOL;
$str .= 'Atlético'.PHP_EOL;
$str .= 'Santos'.PHP_EOL;

echo $str;
// Mosta: Flamengo Vasco Botafogo Atlético Santos

echo nl2br($str);
/* Mostra:
Flamengo
Vasco
Botafogo
Atlético
Santos
*/

The constant PHP_EOL represents a line break according to the operating system running PHP. If Windows: \r\n, if UNIX: \n and if MAC: \r.

Recommended reading: PHP: Predefined Constants;

Recommended reading: PHP: nl2br


Nothing stops you from putting some character between each value and then replacing it with an HTML line break:

<?php
$str = 'Flamengo'.'+';
$str .= 'Vasco'.'+';
$str .= 'Botafogo'.'+';
$str .= 'Atlético'.'+';
$str .= 'Santos'.'+';

echo $str;
// Mosta: Flamengo+Vasco+Botafogo+Atlético+Santos+Flamengo

echo str_replace('+', '<br>', $str);
/* Mostra:
Flamengo
Vasco
Botafogo
Atlético
Santos
*/

But think to me: if you have the constant PHP_EOL made for line breaks, why use any character to do her service?!

Not to mention if you enter some value that contains such a character, it will be transformed into a line break!


"- Works in column varchar?" - Sam

Yes! It works! See:

mysql> EXPLAIN `quebra_ln`;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| valores | varchar(100) | YES  |     |         |       |
+---------+--------------+------+-----+---------+-------+
1 row in set (0.14 sec)

mysql> SELECT * FROM `quebra_ln`;
+-----------------------------------------------+
| valores                                       |
+-----------------------------------------------+
| Flamengo
Vasco
Botafogo
Atlético
Santos
 |
+-----------------------------------------------+
1 row in set (0.00 sec)

In PHP, you can run this script to confirm:

<?php
$mysql = new \PDO(...);

$valor1 = 'Flamengo'.PHP_EOL;

$mysql->query("INSERT INTO `quebra_ln` VALUES ('$valor1');");

$valor2 = 'Vasco'.PHP_EOL;
$valor3 = 'Botafogo'.PHP_EOL;
$valor4 = 'Atlético'.PHP_EOL;
$valor5 = 'Santos'.PHP_EOL;

$mysql->query("UPDATE `quebra_ln` SET `valores` = CONCAT(`valores`, '$valor2');");
$mysql->query("UPDATE `quebra_ln` SET `valores` = CONCAT(`valores`, '$valor3');");
$mysql->query("UPDATE `quebra_ln` SET `valores` = CONCAT(`valores`, '$valor4');");
$mysql->query("UPDATE `quebra_ln` SET `valores` = CONCAT(`valores`, '$valor5');");

$select = $mysql->query("SELECT * FROM `quebra_ln`;");

$res = $select->fetch(\PDO::FETCH_ASSOC);

echo nl2br($res['valores']);
/* Mostra:
Flamengo
Vasco
Botafogo
Atlético
Santos
 */

And finally: HTML passes the line breaks normally to PHP by textarea and the like.

This means that if you add the line breaks normally in a textarea, you can store in the database without adding the PHP_EOL. So, when displaying this data, just use the function nl2br().

Ahhhh, and there’s more: if you’re going to display these records in a textarea, do not need to use the function nl2br() to break the lines. The textarea will already take care of breaking such lines for you:

echo '<textarea>';
echo $res['valores'];
echo '</textarea>';

textarea

(Based on the previously exemplified query)

With the contribution of Andrei Coelho.

  • 1

    Works in column varchar?

  • 1

    @Sam nl2br works because it just inserts a <br> into the line break. A string.

  • 1

    @Andreicoelho cashed out! Thanks!

  • 1

    The answer is complete! I would just cite the textarea question that the break already comes automatic. It can catch like this: $text = nl2br($_POST['nomeDoCampo']) ... I love the textarea ! XD

  • 1

    @Lipespry kkkk looks great! Congratulations!

  • Guys, I did not put the code pq by the image I imagined that it was clear that it was a textarea. My mistake. But yes, it is a textarea. And this textarea is sent via post to php, where I use mysqli to update the database. I put team names just to illustrate. The user will be able to enter the text he wants. But of course with the character limit I set in the form and in the database. And it’s a good amount. I thank you all for your help and tomorrow I will try all the valid options that you posted. I stayed for about 9 consecutive hours programming today. Saturei.

  • I updated the question and added the html code and the PHP part that receives the data and performs the query. Ah, and Flamengo and Vasco are together because in the first inserts, I was testing and had not put the space. Only after adding Vasco did I put the space in the code.

  • Guys, I followed @Sam’s idea and added a <br> concatenated with the data that comes from the form in the PHP variable that performs the update. In the database field the <br> appears, but does not disturb so much. The most important thing is that the front is suitable for the user.

  • But now I’m faced with another problem. When the column has the value 'null' in the database, I cannot concatenate with the value coming from the form.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.