dongtong2021 2017-10-16 07:59 采纳率: 0%
浏览 42

如果用户已存在于PHP中,则在将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?

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");
?>
  • 写回答

2条回答 默认 最新

  • doutu1889 2017-10-16 08:27
    关注

    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...
         }
      }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?