Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple rows using a single query

Can Joomla's DB object add multiple rows at once? MySQL can do this like so:

INSERT INTO x (a,b)
VALUES 
 ('1', 'one'),
 ('2', 'two'),
 ('3', 'three')

But can Joomla's own functions achieve the same thing in a single query? Currently I am doing a loop to insert each row (same table) in separate query. Not a good idea when dealing with tons of rows at once.

like image 377
exentric Avatar asked Apr 08 '11 06:04

exentric


1 Answers

You can use:

$db = JFactory::getDbo();
$query = $db->getQuery(true); // !important, true for every new query

$query->insert('#__table_name'); // #__table_name = databse prefix + table name
$query->set('`1`="one"');
$query->set('`2`="two"');
$query->set('`3`="three"');
/* or something like this:
$query->columns('`1`,`2`,`3`');
$query->values('"one","two","three"');
*/

$db->setQuery($query);
$db->query();

and $db->insertId() can return you autoinc id if you have one.

like image 61
Petar Avatar answered Oct 02 '22 13:10

Petar