Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Gibt es eine intelligente Möglichkeit, mehrere Abfragen in MySQL auszuführen, die durch ein Semikolon getrennt sind?

Hier ist eine funktionierende Lösung

<?php
function function_that_does_multiple_queries($mq, $dblink) {
    // if a new line follows the ; then $q_array = explode(';\n',$mq); is suggested since queries can contain ; below
    $q_array = explode(";",$mq);
    /* 
    //To check structure of array
    echo "<pre>";
    print_r($q_array);
    echo "</pre>";
    exit();
    */
    foreach($q_array as $q){
        $q = trim($q);
        $r[] = mysqli_query($dblink,$q);
    }
    return $r;
}
$multi_query = "CREATE TABLE IF NOT EXISTS `stuff_5_firm` (
  `firmid` int(11) NOT NULL,
  `firm_name` varchar(256) NOT NULL,
  `firm_invoice_adr` text NOT NULL,
  `firm_invoice_email` varchar(256) NOT NULL,
  `firm_admin_con_to_userid` int(16) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `stuff_6_invoice` (
  `invoiceid` int(11) NOT NULL,
  `inv_date` datetime NOT NULL,
  `inv_due` datetime NOT NULL,
  `inv_paid` datetime NOT NULL,
  `inv_amount` int(11) NOT NULL,
  `inv_text` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";

function_that_does_multiple_queries($multi_query, $dblink);

?>
"; Ausfahrt(); */ foreach($q_array as $q){ $q =trim($q); $r[] =mysqli_query($dblink,$q); } return $r;}$multi_query ="CREATE TABLE IF NOT EXISTS `stuff_5_firm` ( `firmid` int(11) NOT NULL, `firm_name` varchar(256) NOT NULL, `firm_invoice_adr` text NOT NULL, `firm_invoice_email` varchar (256) NOT NULL, `firm_admin_con_to_userid` int(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;CREATE TABLE IF NOT EXISTS `stuff_6_invoice` ( `invoiceid` int(11) NOT NULL, `inv_date` datetime NOT NULL, `inv_due` datetime NOT NULL, `inv_paid` datetime NOT NULL, `inv_amount` int(11) NOT NULL, `inv_text` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;";function_that_does_multiple_queries($multi_query, $ dblink);?>

Wahrscheinlich ist es klüger, mysqli_multi_query zu verwenden, das hier erklärt wird http://php.net /manual/de/mysqli.multi-query.php (Dank an @andrewsi).