joomlajoomla1.5joomla2.5joomla-dbo

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.


Solution

  • In your model you can do this:

    $db = $this->getDBO();
    $query = "
      INSERT INTO x (a,b)
      VALUES 
      ('1', 'one'),
      ('2', 'two'),
      ('3', 'three')
    ";
    $db->setQuery($query);
    $db->query();
    

    If you are outside your model you need to get the DB object like so:

    $db = JFactory::getDBO();