确实,只能自己封装一个方法来拼sql,比如:
$arr = array('z'=>'ccc','w'=>'ddd')doInsert('aaa', $arr)
doInsert('bbb', $arr)
function doInsert($tbname, $fields) {
$sql = 'insert into ' . $tbname . '('
$sqlfield = ''
$sqlval = ' values('
foreach ($fields as $field => $val) {
if (!empty($sqlfield)) {
$sqlfield .= ','
$sqlval.=','
}
$sqlfield .= $field
$sqlval.='\'' . str_replace('\'', '\'\'', $val) . '\''
}
// 执行拼接好的sql
$this->db->query($sql)
}
迭代时动态组装SQL语句去执行就可以:
$data = [['name' => 'zs', 'addr' => 'china'],
['name' => 'ls', 'addr' => 'china'],
['name' => 'ww', 'addr' => 'china'],
]
foreach ($data as $value) {
$name = $value['name']
$addr = $value['addr']
$sql = "INSERT INTO tablename (name, addr) VALUES ('$name', '$addr')"
$message = add($sql) ? '插入成功' : '插入失败'
echo $message
}
function add ($sql) {
mysql_query($sql)
return mysql_affected_rows()
}
<?php$info=$_POST['info']
$values = ""
for($i = 0 $i < count($info['title']) $i++){
$values .= "('{$info['title'][$i]}', '{$info['price'][$i]}', '{$info['amout'][$i]}'),"
}
$values = rtrim($values, ',')
mysql_query("insert into tablename values ".$values)
//这种情况适用于比较少的行插入
如果数据量比较大
将数据按行存入文本中
for($i = 0 $i < count($info['title']) $i++){$values .= "{$info['title'][$i]}\t{$info['price'][$i]}\t{$info['amout'][$i]}\r\n"
}
file_put_content('data.txt', $values)
mysql_query("load data local infile 'data.txt' into table tablename")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)