使用php将excel中的多行数据导入mysql

时间:2014-05-08 12:57:59

标签: php mysql sql excel

我尝试将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
?>

2 个答案:

答案 0 :(得分:1)

  1. 使用PDO或mysqli并准备好查询。这不仅可以防止SQL注入攻击或其他错误(例如其中包含撇号的单元格),而且您的插入将在循环中更快。

  2. 确保您插入的日期采用Mysql期望的格式,最安全的是YYYY-MM-DD。您可以更新电子表格以使用该格式,也可以在使用PHP DateTime类及其format()方法

  3. 导入日期值时转换日期值

答案 1 :(得分:0)

<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>

和我的PHP代码一样,我使用PHP函数fgetcsv()

<?php 
if(isset($_POST["Import"]))
{
//First we need to make a connection with the database
$host='localhost'; // Host Name.
$db_user= 'root'; //User Name
$db_password= '';
$db= 'product_record'; // Database Name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysql_query($sql);
}
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: index.php');
}
else
echo 'Invalid File:Please Upload CSV File';
}
?>