I searched everywhere in the internet but I couldn't find a perfect solution for my question, regarding on how to validate the CSV Contents before it uploads and save it to database, I am using msqli for the database and PHP for the language script. For example I have 3 columns in localhost database:
These are my following headers I made both in locahost database and in CSV File (1.)Date (2.)Email (3.)Phone Number.
Before uploading and saving to the localhost database it should meet the restrictions of the contents are the ff: For the Date: It should mm/dd/yy ----> 1/31/2018 or 12/31/2018 For the Email: It should name@domain.com ----> saffron@gmail.com For the Number: It should 12 digits number only and the format is ----> 0906-021-0156
If those restrictions meets perfectly the CSV File will be uploaded and save to the database, if not it will throw an error or pop-up message.
I really don't know how to start the execution of program. I am really new to PHP so please help me with this.
This is the code I worked, and I am stack here...
<?php
$dbHost = 'localhost';
$dbUsername = '';
$dbPassword = 'root';
$dbName = 'dbUpload';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Unable to connect database: " . $db->connect_error);
}
if(isset($_POST['submit'])){
$row = 1;
$mycsvfile = array(); //define the main array.
if ($_FILES['csv']['size'] > 0) {
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
$mycsvfile[] = $data; //add the row to the main array.
$headerDate = $mycsvfile[0][0];
$headerEmail = $mycsvfile[0][1];
$headerPhone = $mycsvfile[0][2];
if ($headerDate !== 'Date' || $headerEmail !== 'Email' || $headerPhone !== 'Phone Number') {
$qstring = '?status=invalid_header';
fclose($handle);
}
else {
if ($i > 0) {
$import = "INSERT into upload (techDate, techEmail, techPhone)values('$data[0]','$data[1]','$data[2]')";
$db->query($import);
$qstring = '?status=succ';
}
}
$i++;
}
fclose($handle);
}
else{
$qstring = '?status=err';
}
}
header("Location: uploadvalid.php".$qstring);
?>