mysql批量插入优化


<?php
error_reporting(E_ALL);
$mysqli = new mysqli( "localhost", "root", "", "mongodb");
if (mysqli_connect_errno()) {
        printf( "Connect failed: %s\n", mysqli_connect_error());
        exit();
}
$s = microtime( true);
$datas = array();
for($i=1;$i<=1000000;$i++){
  $datas[$i] = array('username'=> "username".$i,'password'=>md5('username'.$i));
   if($i%1000==0){
    mysql_insert($datas);
    unset($datas);
  }
}
function mysql_insert($datas){
    global $mysqli;
  $values    =    array();
  foreach ($datas as $key=>$data){
    $value     =    array();
    foreach ($data as $k=>$v){
       if(is_scalar($v)) { // 过滤非标量数据
        $value[]     =    ' "'.$v.'"';
      }
    }
    $values[]        = '('.implode(',', $value).')';
  }
  $sql = 'INSERT INTO user (username,password) VALUES '.implode(',',$values);
  $result = $mysqli->query($sql);
   return $result;
   //$result = $mysqli->query($sql);
   if( false !== $result ) {
                        $insertId     =     mysqli_insert_id($mysqli);
                         if($insertId) {
                                 return $insertId;
                        }
                }
  
}
$mysqli->close();
$e = microtime( true);
echo $e - $s;
?>

你可能感兴趣的:(mysql,优化)