在名称列中覆盖的数组值

时间:2018-02-05 13:29:14

标签: php mysql

我想逐个names插入表格。 为什么数组值会在名称列中覆盖黄色插入?(替换)

代码:

<?php

    $conn = new mysqli($servername, $username, "", $dbname);

    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    $value=$_POST['names'];
    $colors = array("red", "green", "blue", "yellow"); 

    foreach ($colors as $value) {

        $query ="insert into test(names) values('$value')";
    }
    if ($conn->query($query) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();
?>

1 个答案:

答案 0 :(得分:2)

每次循环时都会覆盖$query并且只在循环外执行查询

而是在循环中运行查询

<?php

    $conn = new mysqli($servername, $username, "", $dbname);

    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    // Not sure why this is here??
    // as it gets overwriten in your loop    
    $value=$_POST['names'];

    $colors = array("red", "green", "blue", "yellow"); 

    foreach ($colors as $value) {

        $query ="insert into test(names) values('$value')";

        if ($conn->query($query) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

    }
    $conn->close();
?>
  

如果您实际使用的是$value=$_POST['names'];中收集的值,那么您的脚本将对SQL Injection Attack开放   甚至if you are escaping inputs, its not safe!   使用prepared parameterized statements

     

但是你不是这只是一个提醒