How to insert multiple records with 1 insert? [duplicate]

1

I need to insert multiple records with an insert

Example:

$ ids="1,2,3,4"

$conn->prepare("INSERT INTO documento (id) VALUES (1)");
$conn->prepare("INSERT INTO documento (id) VALUES (2)");
$conn->prepare("INSERT INTO documento (id) VALUES (3)");
$conn->prepare("INSERT INTO documento (id) VALUES (4)");

Is there a loop that for example checks how many records I have in my $ ids variable and insert it several times by repeating until I insert the last record of the variable $ ids

    
asked by anonymous 30.06.2018 / 02:10

2 answers

1

In addition to the links indicated in the comments. For your case, you can do so:

$ids = "1,2,3,4";
$idsArray = explode(",", $ids);
$query = "INSERT INTO documento (id, data) VALUES ";
foreach($idsArray as $id){
    $query .= "($id, now()),";
}
$query = substr($query, 0, -1);
$conn->prepare($query);

The string $query looks like this:

INSERT INTO documento (id) VALUES (1,2018-06-29),(2,2018-06-29),(3,2018-06-29),(4,2018-06-29)
    
30.06.2018 / 03:00
1

I leave an alternative.

You can use the array_map function to iterate through the array and apply a function to each element. The function for your view will perform its role:

array_map(function($id) { return "($id, now())"; }, explode(",", $ids))

The function array_map will return an array:

Array
(
  [0] => (1, now())
  [1] => (2, now())
  [2] => (3, now())
  [3] => (4, now())
)

Then, just merge the elements using the function implode separating them by the comma:

/ p>

implode(', ', array_map(function($id) { return "($id, now())"; }, explode(",", $ids)))

Complete code:

$ids = "1,2,3,4";
$query = "INSERT INTO documento (id, data) VALUES " . implode(', ', array_map(function($id) { return "($id, now())"; }, explode(",", $ids)));
$conn->prepare($query);

output from $query mounted:

INSERT INTO documento (id, data) VALUES (1, now()), (2, now()), (3, now()), (4, now())

See working at repl.it

References:

30.06.2018 / 05:21