(PDO PHP) The fastest way to update or insert mult

2020-05-06 13:16发布

问题:

I don't know how to update or insert multiple rows by using PDO. Please help me.

Something that is in my mind is:

$stmt = $dbh->query("update_line_1; update_line_2; update_line_3");
//update_line_1: update table a set a.column1 = "s1" where a.id = 1
//update_line_2: update table a set a.column1 = "s2" where a.id = 2
//....

$stm = $dbh->query("insert_line_1; insert_line_3; insert_line_3");
//something is like the update line above.

I don't know this way works or not. And If you have another way, please let me know. Thank you so so much.

And if I use prepare statement, I just update each row each time. (This is much more safe than above)

$stmt = $dbh->prepare("update table a set a.colum1 = :column1 where a.id = :id");
$stmt->bindParam(":column1","s1");
$stmt->bindparam(":id",1);
$stmt->execute();

The most hate thing I don't want to do is using a loop goes through all elements in an array, and update or insert each element each time

Is another way to mass safely update or insert multiple rows to database? thank for your help.

Sorry about my English.

回答1:

For inserts, you can insert multiple rows worth of data with the following syntax:

INSERT INTO table (col1, col2, col3)
VALUES
    ('1', '2', '3'),
    ('a', 'b', 'c'),
    ('foo', 'bar', 'baz')

For updates, the update will by default effect as many rows as meet the criteria of the query. So something like this would update an entire table

UPDATE table SET col = 'a'

If you are trying to update different values for each row, you don't really have much of a choice other than to do a query for each operation. I would suggest however that, building on your PDO example, you could do something like this:

$update_array = array(
    1 => 'foo',
    2 => 'bar',
    10 => 'baz'
); // key is row id, value is value to be updated

$stmt = $dbh->prepare("UPDATE table SET column1 = :column1 where id = :id");
$stmt->bindParam(":column1",$column_value);
$stmt->bindparam(":id",$id);
foreach($update_array as $k => $v) {
    $id = $k
    $column_value = $v;
    $stmt->execute();
    // add error handling here
}

With this approach you are at least leveraging the use of the prepared statement to minimize query overhead.



标签: php pdo