如何在MySQL的每一行中插入file_name作为值?

时间:2018-11-05 06:33:24

标签: php mysql

我的趋势表中有此结构,我正在将一个csv文件上传到mysql服务器。我想将我的file_name插入每一行的date_sourced中。如何将文件名作为date_sourced列的值

示例 2018-10-02_trx_result.csv是文件的名称,因此,在上传csv时,应在每一行都放置2018-10-02

date_sourced : date
sha1: varchar(255)
vsdt: varchar(255)
trendx:varchar(255)
notes:varchar(255)

PHP代码,用于上传我的CSV。

<?php
if(isset($_POST['submit'])) {
    $host = 'localhost';
    $user = 'root';
    $password = '';
    $db = 'jeremy_db';
    ini_set('max_execution_time', 500);
    $con = mysqli_connect($host,$user,$password) or die('Could not' .mysqli_error($con));

    mysqli_select_db($con, $db) or die ('Could not' .mysqli_error($con));

    $file = $_FILES['file']['tmp_name'];
    $handle = fopen($file, "r");
    ini_set ('memory_limit', filesize ($file) + 4000000);
    $c = 0;

    while(($csvdata = fgetcsv($handle,10000,","))!== FALSE){
        $sha1 = $csvdata[0];
        $vsdt = $csvdata[1];
        $trendx  = $csvdata[2];

        $sql = "INSERT INTO jeremy_table_trend (sha1,vsdt,trendx) VALUES ('$sha1','$vsdt','$trendx')";
        $query = mysqli_query($con , $sql);

        $c = $c+1;
    }
    if($query){
        echo '<script type="text/javascript">'; 
        echo '      alert("CSV uploaded to server");'; 
        echo '      window.location.href = "trendx.php";';
        echo '</script>';
    }
    else { 
        echo "SLAM";
    }
}
?>

HTML代码:

<form id = "myForm" class="ui input" enctype="multipart/form-data" method = "POST" action="trend_upload_csv.php" role = "form">
     <input type = "file" name ="file" id="file" size = "150">
     <input id="myBtn"  class="ui small red button" type = "submit" class = "btn btn-default"  name ="submit" onclick = "myFunction();" value = "Upload CSV"  disabled  /> 
</form>

请帮助我,我不知道如何修剪文件名并将文件名插入mysql:(

2 个答案:

答案 0 :(得分:1)

如果文件名的格式为2018-10-02_trx_result.csv(即日期后跟_,然后是名称的其余部分),则可以使用explode提取日期部分:

list($date) = explode('_', $_FILES['file']['name']);

然后,您可以仅编辑查询以包含$date的值:

$sql = "INSERT INTO jeremy_table_trend (date,sha1,vsdt,trendx) 
        VALUES ('$date','$sha1','$vsdt','$trendx')";

请注意,您实际上应该使用准备好的语句来防止(例如)使数据值中包含单引号以及其他可能的SQL注入攻击。参见this answer

答案 1 :(得分:0)

您可以这样做,

$date = explode("_", !real filename here!)[0];

您可以直接在您的sql语句中插入$date。另外,请确保文件中的日期格式始终为YYYY-MM-DD