使用单个查询插入多行

exe*_*ric 8 joomla joomla1.5 joomla2.5 joomla-dbo

Joomla的DB对象可以一次添加多行吗?MySQL可以这样做:

INSERT INTO x (a,b)
VALUES 
 ('1', 'one'),
 ('2', 'two'),
 ('3', 'three')
Run Code Online (Sandbox Code Playgroud)

但Joomla自己的函数可以在单个查询中实现相同的功能吗?目前我正在做一个循环,在单独的查询中插入每一行(同一个表).在同时处理大量行时不是一个好主意.

Mar*_*tin 7

在您的模型中,您可以这样做:

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

如果您不在模型之外,则需要获取DB对象:

$db = JFactory::getDBO();
Run Code Online (Sandbox Code Playgroud)


Pet*_*tar 6

您可以使用:

$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();
Run Code Online (Sandbox Code Playgroud)

并且$db->insertId()如果你有,可以返回你的autoinc id.


小智 5

如果您在数组中有值,请尝试此操作:

$query = $this->db->getQuery(true);
$query->insert($this->db->quoteName('#__table_name'));
$query->columns($this->db->quoteName(array('col_1','col_2','col_3','col_4')));

for($i=0; $i < lengthOfArray; $i++)
{
    $values= $arr_1[$i].','.$this->db->quote($arr_2[$i]).','.$this->db->quote($arr_3[$i]).','. $arr_4[$i];
    $query->values($values);
}
$this->db->setQuery($query);
$result = $this->db->query();
Run Code Online (Sandbox Code Playgroud)