$st = $dbh->prepare("UPDATE items SET some_id = ? WHERE id = ?");
foreach ($items as $key => $val)
$st->execute(array($key, $val));
Is there a more efficient solution?
$st = $dbh->prepare("UPDATE items SET some_id = ? WHERE id = ?");
foreach ($items as $key => $val)
$st->execute(array($key, $val));
Is there a more efficient solution?
Well it is all about size ;)
If you want to INSERT
milions of rows you should:
CREATE TABLE items_copy LIKE items
or similar.items_copy
items_copy
FROM CSV file: http://dev.mysql.com/doc/refman/5.0/en/loading-tables.htmlUPDATE SET
combined with SELECT * FROM items_copy
DROP TABLE items_copy
If you want to insert just couple of thousands rows you should combine your query into one big string and do it in transaction, like:
$q = 'START TRANSACTION;';
$q .= 'UPDATE items SET some_id = ? WHERE id = ?;';
$q.= 'UPDATE items SET some_id = ? WHERE id = ?;';
....
$q .= 'COMMIT;';
And then execute $q
. The reason you should do that is connecting to database for each query will ruin effectiveness.
Otherwise you foreach function will be just fine.
Hmmm maybe,
$dbh->beginTransaction();
$dbh->exec('LOCK TABLES items');
$st = $dbh->prepare("UPDATE items SET some_id = ? WHERE id = ?");
foreach ($items as $key => $val)
$st->execute(array($key, $val));
$dbh->commit();
$dbh->exec('UNLOCK TABLES');