我尝试将 excel 导入到具有不同数据类型的 mysql 表,包括日期时间列,但代码似乎只选择 excel 数据的第一行并且日期显示为:0000-00-00。如果重复 trade_number($emapData[2]),我如何确保文件不会上传,因为这是我的数据库表中的主键?我确实需要帮助来解决这个问题。
我的 HTML 是这样的:
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-content">
<h1>Traded Securities Data Upload</h1>
<div><label for="exampleInputFile">File Upload: </label><br><input type="file" name="file" id="file"><p style="font-size: .8em; color: rgb(51,0,255);">Only Excel/CSV File to be uploaded.</p></div>
<div><button type="submit" id="Import" class="btn btn-default" name="Import" value="Import">Upload</button></div>
</div><!--end of form content div--><br class="clear-fix">
</form>
而我的 PHP 代码块是
<?php
if(isset($_POST["Import"])){
// Connnection string to the database
mysql_select_db($database_connect, $connect);
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE){
//print_r($emapData);
//exit();
$count++;// add this line
if($count>1){// add this line
$sql = mysql_query("INSERT into trades_data(symbol,trade_date,trade_number,buy_order_date,buy_order_number,sell_order_date,sell_order_number,sell_account,buy_account,buy_firm,sell_firm,buy_firm_name,sell_firm_name,entry_time,price,quantity,settle_date,trade_value,settlement_value,updated) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]','$emapData[8]','$emapData[9]','$emapData[10]','$emapData[11]','$emapData[12]','$emapData[13]','$emapData[14]','$emapData[15]','$emapData[16]','$emapData[17]','$emapData[18]',now())") or die (mysql_error());
mysql_query($sql);
} // if count closed // add this line
} //while loop closed
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: ../edit_pages.php');
}
else{
echo 'Invalid File:Please Upload CSV File';}
} // close first if
?>
最佳答案
使用 PDO 或 mysqli 和准备好的查询。这不仅可以防止 SQL 注入(inject)攻击或其他错误(例如其中包含撇号的单元格),而且您的插入在循环中会更快。
确保您插入的日期采用 Mysql 期望的格式,最安全的格式是 YYYY-MM-DD。要么更新电子表格以使用该格式,要么在使用 PHP 的
DateTime
类及其format()
方法 导入电子表格时转换日期值
关于php - 使用php将excel中的多行数据导入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23542444/