How do I handle Variables in PHP?

Asked

Viewed 105 times

0

I have the following code in PHP:

Array:

$eqCodigos  = $_POST["eqCodigo"];

Treatment Attempt to save 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 from 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');

But at the time saved in the bank the first code of the Array is with " r" at the end, making it difficult at the time I will make the Select.

  • You can use a regular expression to remove where you have the /r $ret = preg_split ('/$\R?^/m', $eqCodigos);

  • But I can leave the Code the way this or I can use that expression instead of Trim?

  • 1

    @Flaviomisawa what this Regex was to do? ^ starting at the end?

  • \r or /r? which one of them

  • @Wallacemaxters is r, I edited the question and put the table export after Insert for you see how it looks in Mysql.

1 answer

3


First I’d like to point out some errors in your code, so we can look at 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 be done in this 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 verify that some operating systems break line is \r\n, and 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 "was left behind". My solution to this, would be to first treat the data, so that they are standardized to \n at all times.

That is to say:

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

If you want to resubmit the variable declaration process, you can still do so:

$eqCodigo = array_map('trim', array_filter(explode("\n", str_replace("\r\n", "\n", $eqCodigos))));
  • Thank you very much for your Solution and explanation helped me a lot. I managed to solve the problem! Using the summary you passed!

Browser other questions tagged

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