Create a html form that accepts a file
When the page loads check to see if the submit button has been pressed
Check the file type is a csv by exploding the file name
Read through the document line by line using a handler and storing each column in a variable
mysqli_real_escape_string($conn, $data[0]); this removes any white space and special characters for security
Write data into the database using sql and repeat steps of reading each line
<?php
include('connect.php');
//check to see if form sent
if(isset($_POST["submit"])){
if($_FILES['file']['name']){
echo($_FILES['file']['name']);
$filename = explode(".",$_FILES['file']['name']);
//check to see if file name has a csv extension_loaded
if($filename[1] =='csv'){
//create a handler to read through file
$handle =fopen($_FILES['file']['tmp_name'],"r");
//read through the document and grab each cell and store in a local variable
while($data =fgetcsv($handle)){
$first = mysqli_real_escape_string($conn, $data[0]);
$last = mysqli_real_escape_string($conn, $data[1]);
$year = mysqli_real_escape_string($conn, $data[2]);
$gender = mysqli_real_escape_string($conn, $data[3]);
$activity = mysqli_real_escape_string($conn, $data[4]);
//create a sql statement with variables for insert
$sql = "insert into sa_activities(first, last, gender, year,activity) values ('$first','$last','$gender','$year','$activity')";
if($conn->query($sql) === true){
echo("New record added");
}else{
echo $sql." ". $conn->error;
}
}
//close the handler
fclose($handle);
//let the user know they are done
echo("<script>alert('import done')</script>");
}
}
}
?>
<html>
<body>
<h3 align="center">Import Sport Activities Data from CSV</h3>
<form method="POST" enctype="multipart/form-data">
<label>Select CSV File:</label>
<input type ="file" name="file"/>
</br>
<input type="submit" name="submit" value="Import"/>
</form>
</body>
</html>