Home > Database > Mysql Tutorial > body text

PDO MySQL: How to Insert Multiple Rows in One Query Without 'Array to string conversion' Error?

Susan Sarandon
Release: 2024-11-07 04:57:02
Original
625 people have browsed it

PDO MySQL: How to Insert Multiple Rows in One Query Without

PDO MySQL: Insert Multiple Rows in One Query

Question:

In a PDO class designed for multiple insert, despite creating a parameterized query, an "Array to string conversion" error occurs when executing the query. How can this error be resolved?

Answer:

To resolve this error, one approach is to iterate through the data array and bind the values one by one using bindValue instead of binding the entire array. This ensures that each value is properly bound to a specific parameter.

Here's an example of implementing this approach:

$query = "INSERT INTO $table (key1, key2, key3) VALUES ";
$qPart = array_fill(0, count($data), "(?, ?, ?)");
$query .= implode(",", $qPart);
$stmt = $this->start->prepare($query);
$i = 1;
foreach ($data as $item) { 
    $stmt->bindValue($i++, $item['key1']);
    $stmt->bindValue($i++, $item['key2']); 
    $stmt->bindValue($i++, $item['key3']);
}
$stmt->execute();
Copy after login

Alternatively, you can use the foreach loop inside the prepare statement to bind values for each row:

$stmt = $pdo->prepare("INSERT INTO foo VALUES (1, 2, 3)");
foreach($data as $item) {
    $stmt->execute($item);
}
Copy after login

This approach executes the query multiple times, one for each row. However, it is simpler to implement than the former approach.

The above is the detailed content of PDO MySQL: How to Insert Multiple Rows in One Query Without 'Array to string conversion' Error?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!