Jan Aranas Jan Aranas - 7 months ago 18
PHP Question

PHP syntax only store last value of the array

need help with this syntax it only stores the last value of my array into the database.

<?php
if(isset($_POST["submit"])) {
$lines=preg_split('/\r\n|[\r\n]/', $_POST['text']);


foreach($lines as $line => $value)
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}

}
?>

Answer

You should add bracket to your foreach. Without that, only the next line will be in the loop.

so you should have:

foreach($lines as $line => $value) {
    $quer = "INSERT INTO wew (wewe) VALUES('$value')";
    if ($conn->query($quer) === TRUE) {
      echo "New record created successfully";
    }
}

I advice you to use bracket for all your conditions and loops since the readability is better and you avoid errors like that.