我将数据从CSV文件导入Mysql数据库。代码工作正常,但它不插入第一行csv文件。
<?php
if(isset($_POST["Import"]))
{
//First we need to make a connection with the database
$host='localhost:3311'; // Host Name.
$db_user= 'root'; //User Name
$db_password= 'root';
$db= 'compared'; // Database Name.
$connect=mysqli_connect($host,$db_user,$db_password,$db);
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$csv_file = $filename; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile))
{
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['0'] = $csv_array[0];
$insert_csv['1'] = $csv_array[1];
$insert_csv['2'] = $csv_array[2];
$insert_csv['3'] = $csv_array[2];
$insert_csv['4'] = $csv_array[2];
$query = "INSERT INTO reviews(id,userid,title, review, rating)
VALUES('".$insert_csv['0']."','".$insert_csv['1']."','".$insert_csv['2']."','". $insert_csv['3']."','".$insert_csv['4']."')";
$n=mysqli_query($connect,$query );
$i++;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
}
}
?>
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>
这是数据
1,2,abc,abc,3
2,3,abc,abcd,5
11,2,abc,abc,3
22,3,abc,abcd,5
从第二行插入并跳过第一行。任何人都可以解决它吗?
答案 0 :(得分:4)
您在循环外执行第一个fgets
,然后在循环开始之后立即执行另一个,从而跳过第一个结果。
do-while构造应解决您的问题:
$theData = fgets($csvfile);
do {
// Extract data from $theData
// Insert into the database
// Get the next line:
$theData = fgets($csvfile);
} while (!feof($csvfile));