我从网上收集了一些资料,编写了这个小脚本,将 CSV 文件导入 MySQL 数据库。我认为这是正确的,但它不起作用。
我究竟做错了什么?
<?php
//connect to the database
$connect = mysql_connect("localhost","testdb","testdb");
mysql_select_db("testdb",$connect); //select the table
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO class12 (htno, subcode, subname, int_marks, ext_marks, result, credits) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
'".addslashes($data[3])."'
'".addslashes($data[4])."'
'".addslashes($data[5])."'
'".addslashes($data[6])."'
'".addslashes($data[7])."'
)
");
}
} while ($data = fgetcsv($handle,3000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
如果可能,请包含代码以使用文件名(不带.csv
扩展名)自动创建 SQL 表,然后将其导入。