MarkJane
4/18/2017 - 2:31 AM

mysqli mutiquery 执行多条sql语句

mysqli mutiquery 执行多条sql语句

<?php
$mysqli=new MySQLi("localhost","root","","db");   
  
 /*==========================没有结果集:insert update delete==========================*/    
  $sqls="insert into shops(name,price,num,desn) values('book1','12.16','5','good');";      
  $sqls.="updated shops set name='testname' where id>50;";      
  $sqls.="delete from shops where id < 20";          
  if($mysqli->multi_query($sqls))  
  {          
    echo "多条语句执行成功!<br>";              
    echo "最后插入的ID:".$mysqli->insert_id."<br>";         
    echo "影响的行数:".$mysqli->affected_rows;  //不准确!      
  }  
  else  
  {         
    echo "ERROR".$mysqli->errno."---".$mysqli->error;      
  }                 
   /*==========================有结果集:select==========================*/      
  $sqls="select current_user();";      
  $sqls.="desc shops;";      
  $sqls.="select * fron shops";         
   if($mysqli->multi_query($sqls))  
   {         
    echo "多条语句执行成功!<br>";          
    do  
    {              
        $result=$mysqli->store_result();   //获取结果集                         
         echo '<table border="1" align="center">';              
         echo '<tr>';              
         while($field=$result->fetch_field()){                  
            echo '<th>'.$field->name.'</th>';              
         }            echo '</tr>';                         
          while($row=$result->fetch_assoc()){                  
            echo '<tr>';                  
            foreach($row as $col)  
            {                      
                echo '<td>'.$col.' </td>';                  
            }                  
            echo '</tr>';              
          }              
          echo '</table>';                         
           if($mysqli->more_results()){   //判断还有没有结果集                 
             echo "<br><br><br>";                  
           }                      
    }  
    while($mysqli->next_result());    //取得下一个结果集     
    }  
    else{        echo "ERROR".$mysqli->errno."---".$mysqli->error;      
    }              
    $mysqli->close();
?>