CSV file import and export database database

Example one:

<?php
$filename = 'test';
//导出文件
header("Content-type: application/vnd.ms-excel; charset=utf-8");
Header("Content-Disposition: attachment; filename=".$filename.".csv");

echo "product name, product number, product price, product brand, product color \ the n-";

$ arr = [
[ 'mink autumn 1', 'dq00001', ' 1000', ' Diaopai', 'red'],
[ 'mink autumn 2', 'dq00002', ' 1000', ' Diaopai', 'blue'],
[ 'mink autumn 3', 'dq00003', ' 1000', ' Diaopai', 'green'],
[ 'mink autumn 4', 'dq00004', ' 1000', ' Diaopai', 'white']
];
// loop through the array and outputs
the foreach (ARR $ $ Item AS) {
echo the implode ( ',', . Item $) "\ n-";
}

 

Example Two:

// exported from the database

$ Conn = mysqli_connect ( 'localhost', 'root', '123456', 'st0614'); // connect to the database

$filename = 'student';//文件名为student
header("Content-type: application/vnd.ms-excel; charset=utf-8");
Header("Content-Disposition: attachment; filename=".$filename.".csv");

mysqli_query RES = $ ($ conn, 'the SELECT * from Student');
echo "ID, name, sex, age, faculty, classes, head \ n"; // header
while ($ row = mysqli_fetch_assoc ($ res) ) // Get database data
{
$ ARR [] = $ Row;
}
the foreach (ARR $ $ Item AS) {
echo The implode ( ',', Item $) "\ n-";. // output
}

// SVN import database

$file = 'text.txt';
if (isset($_POST['commit'])){
$file = $_FILES['csv'];
$fileName=$file['tmp_name'];

$fp = fopen($fileName,'r');
$i=0;
while ($file_data = fgetcsv($fp))
{
$i++;
if($i==1)
{
continue;//过滤表头
}else{
$data[$i] = $file_data;
}

}
fclose($fp);
}

<----------- Separate the ----------->
// stored in the database
IF (isset ($ Data)) {
the foreach (AS $ $ Data Item) {
   $ = iconv name ( 'GB2312', 'UTF-. 8', Item $ [. 1]);
   $ SQL = "INSERT INTO Student (name``, `sex`, age``, `d_id`, class_id``, ` tumble`) values ( '{$ name }', {$ item [2]}, {$ item [3]}, {$ item [4]}, {$ item [5]}, '{$ item [6 ]} ') ";
   $ RES = the mysqli_query (Conn $, $ SQL);
}
 IF ($ RES) {
   echo' success! ';
 } The else {
   echo' Upload failed! ';
 }
}

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>

<form action="" method="post" enctype="multipart/form-data">
csv文件:
<input type="file"name="csv">
<--<button id="btn" onclick="<?php //download(); ?>">下载</button>-->
<input type="submit" name="commit" value="上传">
</form>

</body>
</html>

Guess you like

Origin www.cnblogs.com/yinfa/p/11267198.html