Home  >  Article  >  Backend Development  >  thinkphp3.2.3 表单验证 unique报错

thinkphp3.2.3 表单验证 unique报错

WBOY
WBOYOriginal
2016-06-20 12:47:141197browse

protected $_validate = array(    // array(field,rule,message,condition,type,when,params)        // 1 用户不能为空,唯一,至少4个字符        array('username', '', '用户名已存在', 0, 'unique'),    );

在表单输入相同的名字 报SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '100' for key 'PRIMARY'
数据库相同的名字的位置,而不是输出错误信息。这是那里错了?


回复讨论(解决方案)

报错提示: Integrity constraint violation: 1062 Duplicate entry '100' for key 'PRIMARY'
该是整型的主键字段。而你给了字符串'100'。什么情况

主键id100那行的username是相同的输入
而且还有一个错误
所有错误消息都报非法数据对象!

请贴出控制器里处理表单的代码

是控制器里处理表单代码逻辑错了
        $user = new \Model\UserModel();
        
        if (!empty($_POST)) {
            $_POST['user_hobby'] = implode(',', $_POST['user_hobby']);
            
            // create方法收集表单信息并返回,同时触发表单自动验证
            $data = $user->create();    //  model设置$_validate // 如果设置了数据自动验证则进行数据验证
              if ($user->add($data)) {
                  echo '添加数据成功';
              } else {
                  dump($user->getError());
              }
        } else {
            $this->display();
        }
    }

改成
 if ($data) {
                  echo '添加数据成功';
              } else {
                  dump($user->getError());
                  return;
              }
              $user->add($data);
就好了,
不过为什么会这样

打印出$data看看,给出表结构。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn