I’m working on remodeling my import code in one of my programs which looks like this:
<?php
include('dbconnect.php');
if(isset($_POST['btn_upload'])){
$filename = $_FILES['file']['tmp_name'];
$file = fopen($filename,"r");
// Read and throw away the header row
fgetcsv($file);
$stmt = $pdo->prepare("INSERT INTO contacts (id, last_name, first_name,
middle_name, suffix, residential_address, mailing_address, precinct, age,
ethnicity, gender, race, status, phone, reg_date)
VALUES (:id, :last_name, :first_name, :middle_name, :suffix,
:residential_address, :mailing_address, :precinct, :age, :ethnicity,
:gender, :race, :status, :phone, :reg_date)");
while (! feof($file)) {
$row = fgetcsv($file);
if($row[0] == NULL) {
continue;
}
$stmt->bindParam(':id', $row[0]);
$stmt->bindParam(':last_name', $row[1]);
$stmt->bindParam(':first_name', $row[2]);
$stmt->bindParam(':middle_name', $row[3]);
$stmt->bindParam(':suffix', $row[4]);
$stmt->bindParam(':residential_address', $row[5]);
$stmt->bindParam(':mailing_address', $row[6]);
$stmt->bindParam(':precinct', $row[7]);
$stmt->bindParam(':age', $row[8]);
$stmt->bindParam(':ethnicity', $row[9]);
$stmt->bindParam(':gender', $row[10]);
$stmt->bindParam(':race', $row[11]);
$stmt->bindParam(':status', $row[12]);
$stmt->bindParam(':phone', $row[13]);
$date = date_create($row[14]);
$dfstr = date_format($date, 'Y-m-d');
$stmt->bindParam(':reg_date', $dfstr);
$stmt->execute();
}
fclose($file);
header("Location: ../contacts_list.php");
}
if(isset($_POST['btn_back'])) {
header("Location: ../contacts_list.php");
}
?>
I have a few items in this code that I’m wanting to change:
-
Instead of clicking a button to read an uploaded file, is it possible for the code to read a file that is saved in the server automatically or is this not recommended? I have a file that is downloaded to my server once a week via cron job and would like to use this file since it has official data inside of it rather than try to parse the data myself. Also, this file is a .txt file instead of a .csv file and it is tab separated, not comma separated.
-
Is it possible to filter out certain data that I don’t need before it is imported? For example, there’s a column in this new file called
party
that I need to filter and I’m only interested in records that containREP
in this column. The file contains over 200,000 records and I’m thinking by filter certain columns to get what I need is a good a way to minimize this number as 200,000+ is too much data to use in the site and would likely crash my server. -
Ideally, I would like the database to act as a mirror to the file so that if a record gets deleted or updated, then that change would show in the database after a certain amount of time. Is this possible to do or is it worth the effort?