Insert multiple rows using a single query

exentric picture exentric · Apr 8, 2011 · Viewed 10.7k times · Source

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.

Answer

Martin picture Martin · Apr 8, 2011

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();