3

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!

2
  • You do need to add $connect to your first call to mysqli_query but why did you add the WHERE condition to your second one? Commented Jan 23, 2020 at 23:37
  • @Nick I had two rows with id=1 and id=2. I thought that if I am going to specify an id its going to insert it into one row as an array. I am aware that this is probably wrong anyway ;) Commented Jan 23, 2020 at 23:48

2 Answers 2

1

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')");
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Alberto, So I actually tried doing something like that before but it is giving me this error: "Notice: Undefined index: name" and this one "Warning: Invalid argument supplied for foreach()". Cheers.
Changed the answer since i suspect you may be using the same file/url to render the form and process the insert. Please confirm if this is the case
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.