How do I handle Variables in PHP?

0

I have the following PHP code:

Array:

$eqCodigos  = $_POST["eqCodigo"];

Treatment Attempt to write to MySQl

$eqCodigo1 = explode("\n", $eqCodigos);
$eqCodigo2 = array_filter($eqCodigo1);
$eqCodigo  = trim($eqCodigo2);

Query mysql_query

mysql_query("INSERT INTO eq_Codigos (idEquipamento, cdCodigo, cdOpAlteracao, cdDtAlteracao) VALUES ('$idEquipamento', '$eqCodigo[0]', '$eqOpAlteracao', NOW()), ('$idEquipamento', '$eqCodigo[1]', '$eqOpAlteracao', NOW())")

Export table after INSERT

INSERT INTO 'eq_Codigos' ('idCodigo', 'idEquipamento', 'cdCodigo', 'cdOpAlteracao', 'cdDtAlteracao') VALUES (27, 164, '123\r', 'Jonatas Messias', '2016-09-23 10:06:16'), (28, 164, '987', 'Jonatas Messias', '2016-09-23 10:06:16');

Only when I save in the database the first Array code gets "\ r" at the end, making it difficult to select.

    
asked by anonymous 23.09.2016 / 14:49

1 answer

3

First I would like to point out some errors in your code, to analyze the situation:

$eqCodigo1 = explode("\n", $eqCodigos); // Isso vira um 'array'
$eqCodigo2 = array_filter($eqCodigo1); // Certo, o 'array' será filtrado
$eqCodigo  = trim($eqCodigo2); // Usar trim num 'array' vai gerar erro, pois ele espera uma 'string'.

The first thing to do in case is to change this code to:

$eqCodigo1 = explode("\n", $eqCodigos);
$eqCodigo2 = array_filter($eqCodigo1);
$eqCodigo  = array_map('trim', $eqCodigo2);

One of the situations to be done here is to check that some operating systems break the line is \r\n , not only \n .

When doing a test with the following string :

  explode("\n", "\r\n a" )

The result was:

[
  "\r",
  " a",
]

That is, note that \r "is behind". My solution to this would be to first treat the data so that it gets standardized to \n always.

That is:

  explode("\n", str_replace("\r\n", "\n", $eqCodigos));

If you want to summarize the process of declaring variables, you can still do this:

$eqCodigo = array_map('trim', array_filter(explode("\n", str_replace("\r\n", "\n", $eqCodigos))));
    
23.09.2016 / 15:35