接上篇
一、将用户数据存入数据库
public function runRegis(){
if(!$this->isPost()){
halt('页面不存在');
}
$User= D('User');
$User->createTime=date('Y-m-d H:i:s',time());
$User->modifyTime=date('Y-m-d H:i:s',time());
$result = $User->add();
if($result) {
$this->success('操做成功!');
}else{
echo($result);
}
}
其中用到了TP的D函数,而且有手动给字段赋值的操做。可是若是在add()以前有用create()进行判断,赋值操做就失效了,示例代码以下:
if($User->create()) {
$result = $User->add();
if($result) {
$this->success('操做成功!');
}else{
echo($result);
}
}else{
$this->error($User->getError());
}
赋值操做应该在create以后,修改以下
public function runRegis(){
if(!$this->isPost()){
halt('页面不存在');
}
$User= M('User');
if($User->create()) {
$User->createTime=date('Y-m-d H:i:s',time());
$User->pwd=$this->_post('pwd', 'md5');
$id = $User->add();
if($id) {
session('uid',$id);
//跳转至首页
header('Content-Type:text/html;Charset=UTF-8');
redirect(__APP__, 2,'注册成功,正在为您跳转...');
}else{
halt('操做失败');
}
}
}
二、判断某一字段是否已经存在
/**
* 异步验证字段是否存在是否已存在
*/
public function checkUnique(){
if (!$this->isAjax()) {
halt('页面不存在');
}
$cName = $this->_get('cName');
$cValue = $this->_post($cName);
$where = array($cName=>$cValue);
if(M('user')->where($where)->getField('id')){
echo 'false';
}else {
echo "true";
}
}
TP3.1.3增长了I函数,听说更为安全,是官方推荐使用的,修改写法以下
/**
* 异步验证字段是否已存在
*/
public function checkUnique(){
if (!$this->isAjax()) {
halt('页面不存在');
}
$cName = I('get.cName');
$cValue = I('post.'.$cName);
$where = array($cName=>$cValue);
if(M('user')->where($where)->getField('id')){
echo 'false';
}else {
echo "true";
}
}