1

Good day.

<input type="text" name="title">
<input type="text" name="name[]">
<input type="text" name="name[]">

<?php
if(isset($_POST['submit']){
    $title = $_POST['title'];
    $name = $_POST['name'];

    $add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
}
?>

How can this code work? It should be inserted with same title and different names at the same time. Thank you.

Sample Form

I want the record to be updated as follows:

---------------------------------

|--bookID--|--Title--|--Author--|

|----1-----|---one---|----me----|

|----2-----|---two---|---you----|

---------------------------------

Oween
  • 13
  • 6

4 Answers4

1

$_POST['name'] is an array with key 0,1 ... So in your example you ve got:

 //This is just an example
 foreach($_POST['name'] as $name) {

 }

Hope this helps.

  • Tnx for the reply. But how would be my query looks like? "INSERT INTO books (title,name) VALUES ('$title','$name')". So I can insert two rows with same title and different names? – Oween Jul 24 '18 at 08:58
  • the same query you used before, check @AtulVerakiya's post – Alexandre Painchaud Jul 24 '18 at 09:15
0

Please check below code

if(is_array($_POST['name']) && !empty($_POST['name'])) {
    foreach($_POST['name'] as $name) {
        $add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
    //execute query here. mysqli_query($add) or PDO::query
    }
}
kallosz
  • 521
  • 3
  • 10
0

Atul Vekariya example is correct but you need to also execute the query in the loop. That's why this example did not work for you.

if(is_array($_POST['name']) && !empty($_POST['name'])) {
    foreach($_POST['name'] as $name) {
        $add = "INSERT INTO books (title, name) VALUES ('$title','$name')";

        //execute query here. mysqli_query($add) or PDO::query
    }
}
kallosz
  • 521
  • 3
  • 10
0

After searching different solutions. Here is the one that works. Thank you for all the help.

<?php
include_once 'config/connect.php';

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $title = $_POST['title'];
    $name = $_POST['name'];
    $length = count($name);
    $addBook = "INSERT INTO books (title,name) VALUES ";
    for($i=0; $i<$length; $i++){
        $addBook .= "('$title','$name[$i]'),";
    }
    $addBook = rtrim($addBook, ',');

    if($conn->query($addBook) === TRUE) {
        echo "Success";
    } else {
        echo "Error: ".$addBook."<br>".$conn->error;
    }

}
?>

<form action="addBook.php" method="POST">
    Title: <input type="text" name="title">
    <br/>
    Authors: <input type="text" name="name[]"> <input type="text" name="name[]"> 
    <br/>
    <input type="submit" name="submit">
</form>
Oween
  • 13
  • 6