如果用户已存在于 PHP 中,则在将 Excel 文件数据上传到数据库时显示错误消息 [英] Show the error message while uploading Excel file data to database if user already exist in PHP
本文介绍了如果用户已存在于 PHP 中,则在将 Excel 文件数据上传到数据库时显示错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 phpexcel
库将一些 Excel 数据加载到数据库中,如果用户已经存在,一切正常 - 它没有显示任何错误.
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?
这是我的代码:
<?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");
?>
推荐答案
for ($i = 1; $i <= $arrayCount; $i++) {
...
$resultcheck = $DB->insert_record('user', $insert_record);
if ($resultcheck == false){
header("Location:error.php");
}
}
或者,如果您能够使用 jQuery/AJAX
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
}
这篇关于如果用户已存在于 PHP 中,则在将 Excel 文件数据上传到数据库时显示错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文