Reputation: 31
I have a form with multiple fields like that:
<input type="text" name="name[]" value="">
<input type="text" name="name[]" value="">
<input type="text" name="name[]" value="">
I am trying to insert submit that form and those values to an array in database:
<?php
$i = 0;
foreach ($_POST as $val) {
$name = $_POST['name'][$i];
mysqli_query("INSERT INTO main (name) VALUES ('$name')");
$i++;
}
?>
This is giving me error "mysqli_query() expects at least 2 parameters, 1 given"
I also tried replacing the query with:
mysqli_query($connect, "UPDATE main
SET name='$name'
WHERE id=2");
But I think this is not actually posting 3 values of name to an array. Instead its posting only one.
I tried to use multiple codes that I found on this website but I still can't figure it out!
Upvotes: 3
Views: 228
Reputation: 11
You are looping through $_POST
, there is no need to do that, try looping through $_POST['name']
, like this:
If the file rendering the form is the same one receiving the post you must first validate a post has been made before attempting to loop through 'name'
.
if(array_key_exists('name', $_POST){
foreach($_POST['name'] as $name){
mysqli_query($connect, "INSERT INTO main (name) VALUES
('$name')");
}
}
Upvotes: 1
Reputation: 580
Try with this:
mysqli_query($connect, "INSERT INTO main (name) VALUES ('".$name."')");
Here $connect
is your database connection. you need to specify this connection somewhere earlier in your code.
Upvotes: 0