草庐IT

PHP OOP - 重复记录条目

coder 2023-10-26 原文

我必须在我的 mysql 数据库中创建resumes

我正在使用 PHP OOP,并且我有用户需要填写的表单 register.php

我的目标是:

  1. 只要职位不发送两次,同一用户可以提交多个申请。例如“Thomas 使用 thomas@mail.com 发送第一个申请,id 1111 并且职位为 执行官,但他不能使用相同的电子邮件地址或身份证号第二次提交相同的职位”

有人可以帮忙吗?下面是我的代码。 *注意:我在 Check.php 上遇到问题。我不确定如何检查 case 'duplicate': 区域。

注册.php

<?php
    require_once 'database/connect.php';
    if(isset($_POST['Submit'])) {
        $filter         = new Check();
        $submission     = $filter->filterForm($_POST, array(
            'email'             => array(
                    'required'  => true,
                    'unik'      => 'resumes'
                ),
            'id_number'         => array(
                    'required'  => true,
                    'unik'      => 'resumes'
                ),
            'positions'         => array(
                    'required'  => true,
                    'duplicate' => 'resumes'
                )
        ));
        if($submission->valid()){
            $sender = new Sender();
            try{
                $sender->create(array(
                    'email'         => Input::get('email'),
                    'id_number'     => Input::get('id_number'),
                    'positions'     => Input::get('positions')
                ));
                // header to other location after success
            }catch(Exception $e){
                die($e->getMessage());
            }
        } else {
            foreach($submission->errors() as $error){
                echo $error, '<br>';
            }
        }
    }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Submit Application</title>
</head>
<body>
    <form action="" method="post">
        <table>
            <tr>
                <td>email :</td>
                <td><input type="text" name="email" value=""></td>
            </tr>
            <tr>
                <td>ID Number :</td>
                <td><input type="text" name="id_number" value=""></td>
            </tr>
            <tr>
                <td>Position Applied :</td>
                <td>
                    <select name="positions">
                        <option>Non Executive</option>
                        <option>Executive</option>
                        <option>Management</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><input type="submit" name="Submit" value="Submit Application"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Check.php

<?php
    class Check{
        private $_valid = false,
                $_errors = array(),
                $_db,
                $_count  = 0;
        public function __construct(){
            $this->_db = // Connection to DB using PDO
        }
        public function filterForm($source, $items = array()){
            foreach($items as $item => $rules){
                foreach($rules as $rule => $rule_value){

                    $inputValue = $source[$item];
                    if($rule === 'required' && empty($inputValue)){
                        $this->addError("{$item} is required");
                    } else if(!empty($inputValue)){
                        switch($rule){
                            case 'unik':
                                $checkUnik = $this->_db->get($rule_value, array($item, '=', $value));
                                if($checkUnik->count()){
                                    $this->displayError("{$item} already exists");
                                }
                            break;
                            case 'duplicate':
                                $checkDuplicate = $this->_db->get($rule_value, array($item, '=', $value));
                                if($checkDuplicate->count()){
                                    $checkUsers = $this->_db->query("SELECT * FROM resumes");
                                    if($checkUsers->count()){
                                        $this->displayError("User already apply this positions");
                                    }
                                }
                            break;
                        }
                    }
                }
            }
            if(empty($this->_errors)){
                $this->_passed = true;
            }
            return $this;
        }

        public function valid(){
            return $this->_valid;
        }
        public function errors(){
            return $this->_errors;
        }
        public function displayError($error){
            $this->_errors[] = $error;
        }
        public function count(){
            return $this->_count;
        }
    }
?>

发件人.php

<?php
    class Sender{
        private $_db;
        public function __construct($user = null){
            $this->_db = // Connection to DB
        }
        public function create($fields = array()){
            if(!$this->_db->insert('resumes', $fields)){
                throw new Exception('You have a problem adding information.');
            }
        }
    }

最佳答案

如果我正确理解你的问题,user_id 不应该是 AUTO_INCREMENT。而是制作一个 id 列作为主键并且是 AUTO_INCREMENT :)

这也真的值得通读http://www.phptherightway.com/ :)

关于PHP OOP - 重复记录条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558269/

有关PHP OOP - 重复记录条目的更多相关文章

  1. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  2. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  3. ruby-on-rails - 事件记录 : Select max of limit - 2

    我正在尝试将以下SQL查询转换为ActiveRecord,它正在融化我的大脑。deletefromtablewhereid有什么想法吗?我想做的是限制表中的行数。所以,我想删除少于最近10个条目的所有内容。编辑:通过结合以下几个答案找到了解决方案。Temperature.where('id这给我留下了最新的10个条目。 最佳答案 从您的SQL来看,您似乎想要从表中删除前10条记录。我相信到目前为止的大多数答案都会如此。这里有两个额外的选择:基于MurifoX的版本:Table.where(:id=>Table.order(:id).

  4. Ruby 守护进程导致 ActiveRecord 记录器 IOError - 2

    我目前正在用Ruby编写一个项目,它使用ActiveRecordgem进行数据库交互,我正在尝试使用ActiveRecord::Base.logger记录所有数据库事件具有以下代码的属性ActiveRecord::Base.logger=Logger.new(File.open('logs/database.log','a'))这适用于迁移等(出于某种原因似乎需要启用日志记录,因为它在禁用时会出现NilClass错误)但是当我尝试运行包含调用ActiveRecord对象的线程守护程序的项目时脚本失败并出现以下错误/System/Library/Frameworks/Ruby.frame

  5. ruby-on-rails - 在 Rails 中更高效地查找或创建多条记录 - 2

    我有一个应用需要发送用户事件邀请。当用户邀请friend(用户)参加事件时,如果尚不存在将用户连接到该事件的新记录,则会创建该记录。我的模型由用户、事件和events_user组成。classEventdefinvite(user_id,*args)user_id.eachdo|u|e=EventsUser.find_or_create_by_event_id_and_user_id(self.id,u)e.save!endendend用法Event.first.invite([1,2,3])我不认为以上是完成我的任务的最有效方法。我设想了一种方法,例如Model.find_or_cr

  6. ruby - 在模块/类之间共享全局记录器 - 2

    在许多ruby​​类之间共享记录器实例的最佳(正确)方法是什么?现在我只是将记录器创建为全局$logger=Logger.new变量,但我觉得有更好的方法可以在不使用全局变量的情况下执行此操作。如果我有以下内容:moduleFooclassAclassBclassC...classZend在所有类之间共享记录器实例的最佳方式是什么?我是以某种方式在Foo模块中声明/创建记录器还是只是使用全局$logger没问题? 最佳答案 在模块中添加常量:moduleFooLogger=Logger.newclassAclassBclassC..

  7. ruby - 正则表达式 - 保存重复捕获的组 - 2

    这就是我做的a="%span.rockets#diamonds.ribbons.forever"a=a.match(/(^\%\w+)([\.|\#]\w+)+/)putsa.inspect这是我得到的#这就是我想要的#帮助?我尝试过但失败了:( 最佳答案 通常,您不能获得任意数量的捕获组,但如果您使用扫描,您可以为您想要捕获的每个标记获得一个匹配:a="%span.rockets#diamonds.ribbons.forever"a=a.scan(/^%\w+|\G[.|#]\w+/)putsa.inspect["%span","

  8. ruby - Sinatra 中的全局救援和日志记录异常 - 2

    如何在出现异常时指定全局救援,如果您将Sinatra用于API或应用程序,您将如何处理日志记录? 最佳答案 404可以在not_found方法的帮助下处理,例如:not_founddo'Sitedoesnotexist.'end500s可以通过调用带有block的错误方法来处理,例如:errordo"Applicationerror.Plstrylater."end错误的详细信息可以通过request.env中的sinatra.error访问,如下所示:errordo'Anerroroccured:'+request.env['si

  9. ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录? - 2

    例如,假设我有一个名为Products的模型,并且在ProductsController中,我有以下代码用于product_listView以显示已排序的产品。@products=Product.order(params[:order_by])让我们想象一下,在product_listView中,用户可以使用下拉菜单按价格、评级、重量等进行排序。数据库中的产品不会经常更改。我很难理解的是,每次用户选择新的order_by过滤器时,rails是否必须查询,或者rails是否能够以某种方式缓存事件记录以在服务器端重新排序?有没有一种方法可以编写它,以便在用户排序时rails不会重新查询结果

  10. ruby-on-rails - ActiveRecord 如何将现有记录添加到 has_many :through relationship in rails? 中的关联 - 2

    在我的Rails项目中,我有三个模型:classRecipe:recipe_categorizationsaccepts_nested_attributes_for:recipe_categories,allow_destroy::trueendclassCategory:recipe_categorizationsendclassRecipeCategorization通过这个简单的has_many:through设置,我怎样才能像这样获取给定的食谱:@recipe=Recipe.first并根据现有类别向此食谱添加类别,并在相应类别上对其进行更新。所以:@category=#Exi

随机推荐