Created
February 27, 2018 16:43
-
-
Save ScarletPonytail/44a23b58692d61a74cd248194a92eb53 to your computer and use it in GitHub Desktop.
PHP - Import .csv to database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Attempt MySQL server connection. Assuming you are running MySQL | |
server with default setting (user 'root' with no password) */ | |
$mysqli = new mysqli("localhost", "root", "root", "filmDB"); | |
// Check connection | |
if($mysqli === false){ | |
die("ERROR: Could not connect. " . $mysqli->connect_error); | |
} | |
// die('<pre>'.print_r($_FILES,true).'</pre>'); | |
// File import | |
if(isset($_POST['importSubmit'])){ | |
//validate whether uploaded file is a csv file | |
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'); | |
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){ | |
if(is_uploaded_file($_FILES['file']['tmp_name'])){ | |
//open uploaded csv file with read only mode | |
$csvFile = fopen($_FILES['file']['tmp_name'], 'r'); | |
//skip first line | |
fgetcsv($csvFile); | |
//parse data from csv file line by line | |
while(($line = fgetcsv($csvFile)) !== FALSE) { | |
$mysqli->query("INSERT INTO films (FilmName, FilmGenre, FilmDateAdded) VALUES ('".$line[0]."','".$line[1]."','".$line[2]."')"); | |
} | |
//close opened csv file | |
fclose($csvFile); | |
$qstring = '?status=succ'; | |
} | |
else { | |
$qstring = '?status=err'; | |
} | |
} | |
else { | |
$qstring = '?status=invalid_file'; | |
} | |
} | |
//redirect to the listing page | |
header("Location: ../index.html".$qstring); | |
// Close connection | |
$mysqli->close(); | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Multiple file import --> | |
<h2>Add lots of films</h2> | |
<form id="import-film" class="import-film" action="etc/import.php" name="import-film" method="post" enctype="multipart/form-data"> | |
<div class="form-group"> | |
<input type="file" name="file" /> | |
</div> | |
<div class="form-group"> | |
<input type="submit" class="btn" name="importSubmit" value="Import"> | |
</div> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment