我正在尝试使用phpexcel
库将一些Excel数据加载到数据库中,如果用户已经存在,一切正常 - 它没有显示任何错误。
如果数据库中已存在用户,如何显示错误消息?
这是我的代码:
<?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");
?>
答案 0 :(得分:1)
for ($i = 1; $i <= $arrayCount; $i++) {
...
$resultcheck = $DB->insert_record('user', $insert_record);
if ($resultcheck == false){
header("Location:error.php");
}
}
如果你能使用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 ();
}
}
也许您可以在数据库类中添加一些检查
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
}
答案 1 :(得分:0)
有多种途径可以解决问题。这取决于您的实际代码。
如果您在数据库中将用户名字段设置为唯一,并且您正在使用PDO查询,则无法尝试捕获错误代码:
try{
//Make the insert
}
catch(PDOException $e){
if($e->errorInfo[1] == 1062){
//Duplicated
}
else{
//Other errors...
}
}