-3

I want to insert one by one names in to table. Why array values overwrite in names column just yellow insert?(replace)

Code:

<?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();
?>
Sunil
  • 3,404
  • 10
  • 23
  • 31
Mehmood
  • 3
  • 4

1 Answers1

1

You are overwriting $query each time round your loop and only executing the query outside the loop

Instead run your query inside the loop

<?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();
?>

If you were actually using the value collected in $value=$_POST['names']; then your script is wide open to SQL Injection Attack Even if you are escaping inputs, its not safe! Use prepared parameterized statements

But as you are not this is just a reminder

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149