PHP语法只存储数组的最后一个值

时间:2016-05-04 03:09:32

标签: php mysql

需要这种语法的帮助,它只将我的数组的最后一个值存储到数据库中。

   <?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;
    }

        }
        ?>

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您应该为foreach添加括号。没有它,只有下一行将在循环中。

所以你应该:

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

我建议你为所有条件和循环使用括号,因为可读性更好,你可以避免这样的错误。