摘要:
代码如下:思路:先上车csv文件。再读取临时文件的内容。开始遍历内容,进行拼接,最后通过一条sql语句一次把所有拼接好的数据写入数据库。php<?php  ...
代码如下:
思路:先上车csv文件。再读取临时文件的内容。开始遍历内容,进行拼接,最后通过一条sql语句一次把所有拼接好的数据写入数据库。
php<?php if($_SERVER['REQUEST_METHOD']=='POST'){ function input_csv($handle) { $out = array (); $n = 0; while ($data = fgetcsv($handle, 10000)) { $num = count($data); for ($i = 0; $i < $num; $i++) { $out[$n][$i] = $data[$i]; } $n++; } return $out; } $file = $_FILES['file']['tmp_name']; if(empty($file)){ echo "<script>alert('请选择文件');</script>"; } $handle = fopen($file,'r'); $result = input_csv($handle);//解析csv $len_result = count($result); if($len_result == 0){ echo "<script>alert('没有任何数据');</script>"; }else{ for($i=1;$i<$len_result;$i++){ $sort_num = iconv('gb2312','utf-8',$result[$i][0]); $sf = trim(iconv('gb2312','utf-8',$result[$i][1])); $cs = trim(iconv('gb2312','utf-8',$result[$i][2])); $title = iconv('gb2312','utf-8',$result[$i][3]); $add = iconv('gb2312','utf-8',$result[$i][4]); $ct = iconv('gb2312','utf-8',$result[$i][5]); $phone = iconv('gb2312','utf-8',$result[$i][6]); $flags='i'; $sql = "select id from category where parent_id=(SELECT id FROM category WHERE category_name = '{$sf}') and category_name = '{$cs}'"; $tab_res = $nsodb->get_row($sql,ARRAY_A); $cid = $tab_res['id']; $publisher=$_SESSION['admin']; $data .= "(16,'$cid','$title','$flags','$phone','$sort_num',now(),'$publisher','$add','$ct'),"; } $data = substr($data,0,-1); fclose($handle); $ares = mysql_query("insert into content (channel_id,category_id,title,flags,descriptions,sort_num,add_time,publisher,details,sketch) values $data "); if($ares){ echo "<script>alert('导入成功');</script>"; }else{ echo "<script>alert('导入失败');</script>"; } } } ?>