[英]Better way of uploading csv file to sql database using php
Please help me improve my code. 请帮助我改善代码。 I have this html form to select a .csv file extension only, to upload it in my sql database. 我有此html表单,仅选择.csv文件扩展名,以将其上传到我的sql数据库中。 How can I improve this? 我该如何改善? like make the button not clickable if there is no file chosen. 例如,如果未选择文件,则使按钮不可单击。
<form class="ui input" enctype="multipart/form-data" method = "POST" role = "form">
<input type = "file" name ="file" id="file" size = "150">
<button class="ui small red button" type = "submit" class = "btn btn-default" name ="submit" value = "submit">Upload CSV</button>
</form>
Then this is my php code to upload the csv, How can I make a popup message saying "your file is uploading please wait" and "finished uploading". 然后这是我的php代码,用于上传csv,如何显示“您的文件正在上传,请稍候”和“已完成上传”的弹出消息。 And my problem here is that the headers of my csv file is also uploaded how can I exclude the first row of my csv? 我的问题是我的csv文件的标头也已上传,如何排除csv的第一行?
<?php
if(isset($_POST['submit'])) {
$host = 'localhost';
$user = 'root';
$password = '';
$db = 'jeremy_db';
$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");
$c = 0;
while(($csvdata = fgetcsv($handle,1000,","))!== 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 "SABRE";
}
else {
echo "SLAM";
}
}
?>
I'm using php 7 guys, any suggestions? 我正在使用php 7家伙,有什么建议吗?
Initially you can keep the submit button disable. 最初,您可以禁用“提交”按钮。 Then oclick to input file you can call a js function which will validate file extension and will enable the submit button accordingly. 然后单击以输入文件,您可以调用js函数,该函数将验证文件扩展名并相应地启用提交按钮。
For showing message - you can write a javascript function onclick to submit button. 为了显示消息-您可以编写JavaScript函数onclick提交按钮。
For processing big file on fly this is not a good practice. 对于动态处理大文件,这不是一个好习惯。 It will be timed out to execute all queries(number of queries = number of rows in csv). 执行所有查询都会超时(查询数= csv中的行数)。 You can do this by following below steps - 您可以按照以下步骤进行操作-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.