?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/4/21
* Time: 10:41
*/
header("Content-type: text/html; charset=utf-8");
$mysqli = new mysqli('localhost','root','root','sql');
$mysqli->query('set names utf8');
//批量插入演示
$data[] = array('aa',10);
$data[] = array('bb',20);
$data[] = array('cc',30);
$fields = array('name','score');
$sql = warpSqlByData('bb',$data,$fields);
$falg = $mysqli->query($sql);
if($falg)
{
echo '执行完成';
}
//写一个函数 用来生产多条数据的单句sql
function warpSqlByData($table,$data,$fields)
{
$sql = "INSERT INTO ".$table;
$col_list ='';
$value_list ='';
$fields = array_map('formatclos',$fields);
if(is_array($fields))
{
$col_list = implode(',',$fields);
}
//组织列
$cols = '('.$col_list.')';
$sql = $sql.$cols;
//再来组织value部分
foreach ($data as $value)
{
//判断列的值 进行转化
$value = array_map('formatvalues',$value);
$value_part = implode(',',$value);
$value_list .= '('.$value_part.'),';
}
$value_list = rtrim($value_list,',');
$value_list = ' VALUES'.$value_list;
$sql = $sql.$value_list;
return $sql;
}
//格式化列名
function formatclos($col)
{
return sprintf("`$col`");
}
//格式化列名
function formatvalues($val)
{
return sprintf("'$val'");
}