在php中读取CSV文件

时间:2015-06-30 09:43:14

标签: php mysql

我们可以从每个列的csv文件中读取和删除单引号,双引号和分号,这样就可以将csv文件上传到mysql而不会出现任何错误

 if (isset($_POST['submit'])) {
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
        echo "<h2>Displaying contents:</h2>";
        readfile($_FILES['filename']['tmp_name']);
    }

    //Import uploaded file to Database
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $import="INSERT IGNORE INTO brokers (id,btype,bname,bphone,bmobphone,bfax,bemail,bwebsite,bcompany,bintrowho,bcurrentwho,bintrowhat,baddress,bjobtitle,bregion,bcity,bstate,bzip,bsweetspot1,bsweetspot2,bsweetspot3,bsweetspot4,bsweetspot5,bsweetspot6,bsweetspot7,bsweetspot8,bsweetspot9,bsweetspot10,bsweetspot11,bsweetspot12,bsweetspot13,bsweetspot14,bsweetspot15,baltphone,bdepartment,bitr,bvrr,bskype,bhangouts,bcomments) VALUES ('','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]','$data[36]','$data[37]','$data[38]')";

        mysql_query($import) or die(mysql_error());
    }

    fclose($handle);

    print "Import done";
 $import=header("location:User_option.php");
    //view upload form
}

1 个答案:

答案 0 :(得分:0)

你在这里得到的是SQL injection。这是一种安全可敬性。

在基本术语中,您应该mysql_real_escape_string围绕您正在使用的data[N]引用。例如:

"INSERT IGNORE INTO brokers (id,btype) VALUES ('','mysql_real_escape_string($data[0])')"

请阅读thisthis了解详情。