I recently encountered an issue requiring me to import about 500 employees into a database and add each one to multiple departments.
Using an array, I wrote some pretty simple code to import a CSV file that simply contained “username, real name” into the database.
I wanted to post it in case anyone ever needed to do something along these lines.
<?php
include('../config.php');
$departments = array("department1", "department2", "department3", "department4");
mysql_connect("$dbhost", "$dbuser", "$dbpass") or die(mysql_error());
mysql_select_db("$dbase") or die(mysql_error());
$handle = fopen("employees.csv", "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
foreach ($departments as &$value) {
$query = "INSERT INTO employees (`id`, `name`, `realname`, `tickets`, `dept`) VALUES (NULL, '$data[0]', '$data[1]', '0', '$value')";
$result = mysql_query($query) or die(mysql_error());
echo $data[1] . ' successfully added to ' . $value . ' department<br>';
}
}
unset($value);
?>