I am trying to use the phpexcel
library for loading some Excel data in to a database and everything is working fine if the user already exists - it's not showing any error.
How do I show an error message if a user already exists in the database?
Here is my code:
<?php
require('../config.php');
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
$inputFileName = $_FILES['filename']['tmp_name'];
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
}
catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$arrayCount = count($allDataInSheet);
$ref = 1;
$today = date("Y-m-d H:i:s");
for ($i = 1; $i <= $arrayCount; $i++) {
$username = trim($allDataInSheet[$i]["A"]);
$firstname = trim($allDataInSheet[$i]["B"]);
$lastname = trim($allDataInSheet[$i]["C"]);
$email = trim($allDataInSheet[$i]["D"]);
$password = trim($allDataInSheet[$i]["E"]);
if ($username != '' || $username != 0) {
$insert_record = new stdClass();
$insert_record->username = $username;
$insert_record->email = $email;
$insert_record->firstname = $firstname;
$insert_record->lastname = $lastname;
$insert_record->password = password_hash($password, PASSWORD_DEFAULT);
$insert_record->idnumber = 1;
$insert_record->timecreated = time();
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$resultcheck = $DB->insert_record('user', $insert_record);
}
}
header("Location:user_management.php");
?>
There are multiple paths to solve the problem. It depends on your actual code.
If you set the username field as unique in your database and you're using PDO queries, you can't try and catch the error code:
try{
//Make the insert
}
catch(PDOException $e){
if($e->errorInfo[1] == 1062){
//Duplicated
}
else{
//Other errors...
}
}
for ($i = 1; $i <= $arrayCount; $i++) {
...
$resultcheck = $DB->insert_record('user', $insert_record);
if ($resultcheck == false){
header("Location:error.php");
}
}
OR if you are able to use jQuery/AJAX
for ($i = 1; $i <= $arrayCount; $i++) {
...
$resultcheck = $DB->insert_record('user', $insert_record);
if ($resultcheck == false){
echo json_encode ('Your Error Message.');
exit ();
}
}
Maybe you could add some check in your DB class
public function insert_record($table, $insert_record) {
$sql = "SELECT * FROM users WHERE username =: username";
$statement = $this->db->prepare ( $sql );
$statement->bindValue ( ':username', $insert_record->username, PDO::PARAM_STR );
$statement->execute ();
$result = $statement->fetch ( PDO::FETCH_ASSOC );
if (count($result) > 0){
return false;
}
// Do your other stuff here
}