If you like DNray Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Inserting multiple Mysql records

Started by jameswilliam723, Jan 17, 2023, 03:52 AM

Previous topic - Next topic

jameswilliam723Topic starter

Hey everyone in the forum! I have a question about inserting data into a database using PHP. At the moment, I have a basic script that inserts one record at a time which uses a prepared statement.

$sql = "INSERT INTO orders (title, quantity) VALUES (:title, :quantity)";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":title", $title);
$stmt->bindValue(":quantity", $quantity);
$stmt->execute();

I'm wondering if there's a way to modify this code so that I can insert multiple records in just one request. Could someone please give me some guidance on how to achieve this? Thanks in advance!
  •  

VAnaBB

One possible solution for adding multiple records to a database using PHP is to create a loop that is based on the data that needs to be inserted, allowing for a dynamic query to be built. Although this solution is not directly related to MySQL, it may help solve the client-side problem.

If you're experiencing difficulty with the client-side aspect, it may be best to reach out to the appropriate section or seek guidance from someone who specializes in that area. Remember to always test your code thoroughly before implementing it into production.
  •  

LeonJalp

Here's an alternative method for inserting multiple records into a database using PHP. This example uses an array of orders, where each order is represented as an array containing the title and quantity of the item.

$orders = [
     ['Candy', 5],
     ['Gingerbread', 3],
     ['Buns', 1]
];

$values = str_repeat('(?, ?),', count($orders));
$sql = sprintf("INSERT INTO orders (title, quantity) VALUES %s", rtrim($values, ','));

$stmt = $this->db->prepare($sql);

$stmt->execute(array_merge(...$orders));

This code dynamically builds the SQL query by creating a string of placeholders based on the number of orders and then using these placeholders to construct the SQL query. The data for each order is then flattened into a single array and passed as parameters to the prepared statement execute() method.
  •  

untoneRox

Yes, you can modify your code to insert multiple records in a single request by using prepared statements with parameter binding and executing the statement multiple times with different sets of values. Here's an example:


$sql = "INSERT INTO orders (title, quantity) VALUES (:title, :quantity)";
$stmt = $this->db->prepare($sql);

$data = [
    ["title" => "Product A", "quantity" => 10],
    ["title" => "Product B", "quantity" => 5],
    // Add more data as needed
];

foreach ($data as $row) {
    $stmt->bindValue(":title", $row["title"]);
    $stmt->bindValue(":quantity", $row["quantity"]);
    $stmt->execute();
}

This code uses a foreach loop to iterate through each set of values in the $data array and executes the insert statement for each set of values. You can add as many sets of values as needed to the $data array.

By doing so, you can insert multiple records into the database using a single prepared statement and reduce the number of requests to the database, which can improve performance.

Another approach you can take to insert multiple records in a single request is by using the `INSERT INTO ... VALUES` syntax with `VALUES` separated by commas. Here's an example:


$sql = "INSERT INTO orders (title, quantity) VALUES ";
$values = [];

$data = [
    ["Product A", 10],
    ["Product B", 5],
    // Add more data as needed
];

foreach ($data as $row) {
    $values[] = "(:title, :quantity)";
}

$sql .= implode(", ", $values);
$stmt = $this->db->prepare($sql);

foreach ($data as $index => $row) {
    $stmt->bindValue(":title{$index}", $row
  • );
    $stmt->bindValue(":quantity{$index}", $row[1]);
}

$stmt->execute();

In this code, we construct the INSERT statement dynamically by concatenating the `VALUES` clauses for each set of values. We also bind the parameters with unique names using an incremental index (e.g., `:title0`, `:quantity0`, `:title1`, `:quantity1`, etc.) to ensure uniqueness.

This approach allows you to insert multiple records in a single request, reducing the number of round trips to the database and potentially improving performance.

  •  


If you like DNray forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...