web-dev-qa-db-fra.com

Plusieurs INSERTS dans une requête Joomla

Comment puis-je faire plusieurs inserts comme:

$query = "INSERT INTO `table` (`fied1`, `field2`, `field3`) VALUES ('one', 'two', 'three'),('four', 'five', 'six');
INSERT INTO `table` (`fied1`, `field2`, `field3`) VALUES ('seven', 'eight', 'nine'),('ten', 'eleven', 'twelve');"
$db->setQuery($query);
$db->query();

Je ne peux pas scinder cette requête car elle provient d'un fichier texte volumineux.

Utilisez JDatabaseDriver::splitSql($query) pour que votre fonction ressemble à ceci:

   $query = "INSERT INTO `table` (`fied1`, `field2`, `field3`) VALUES ('one', 'two', 'three'),('four', 'five', 'six');
    INSERT INTO `table` (`fied1`, `field2`, `field3`) VALUES ('seven', 'eight', 'nine'),('ten', 'eleven', 'twelve');";
    $db = JFactory::getDbo();
    $queries = $db->splitSql($query);
    foreach( $queries AS $sql ) {
        $db->setQuery($sql);
        $db->execute();
    }
2
Artur Stępień

Vous pouvez diviser le SQL et exécuter les instructions en utilisant le code ci-dessous

    function insertSql($filename){
        $db = JFactory::getDbo();
        $status = true;

        //parsing of SQL file 
        $sql_file_path = JPATH_ADMINISTRATOR.'/components/xxx/sql/install/mysql/'.$filename.'.sql';
        $queries = JDatabaseDriver::splitSql(file_get_contents($sql_file_path));
        foreach ($queries as $query)
        {
            $query = trim($query);
            if ($query != '' && $query{0} != '#')
            {
                $db->setQuery($query);
                if (!$db->execute())
                {
                    $application->enqueueMessage(JText::sprintf('JLIB_INSTALLER_ERROR_SQL_ERROR', $db->stderr(true)), 'error');
                    $status  = false;
                }
            }
        }
        return $status;
    }
2
Sasi varna kumar

J'utilise une solution de contournement:

$sqlstr = "INSERT INTO `table` (`f1`, `f2`, `f3`) VALUES ('1', 'x', 'p');";
$sqlstr .= "INSERT INTO `table` (`f1`, `f2`, `f3`) VALUES ('1', 'x', 'p');";

[etc.]

$db = JFactory::getDbo();
$m = $db->getConnection();
$m->multi_query($sqlstr);
0
Tim

Essayez ceci

$db = $this->getDBO();  
$query = "INSERT INTO `table` (`field1`,`field2`,`field3`)  
VALUES   
('one', 'two', 'three'),  
('four', 'five', 'six'),  
('seven', 'eight', 'nine'),
('ten', 'eleven', 'twelve')
";  
$db->setQuery($query);  
$db->query(); 
0
Jextn