PHP头条
热点:

ThinkPHP学习笔记1-CURD


ThinkPHP学习笔记1-----CURD

ThinkPHP为我们提供非常快捷的方法执行curd操作,怎么用还是看手册,这里主要写一点我自己经验

例如

(一) 访问:http://localhost:1243/think/index.php/Form/show      显示数据库列表函数

代码如下

        public function show(){
			//进行输出表格
			$user=M("user");
			$userArr=$user->select();
			//dump($userArr);
			$this->assign("userArr",$userArr);
			$this->display();	
		}

1.在M()函数中,user代表的是表名,也就是数据库中的user表.如果无法实例化对象,检查:

  (1).是否在conf/config.php中设置了 ‘DB_DSN’,‘DB_PREFIX’(如果表名存在前缀);

  (2)是否存在 表前缀_user表

2.display(0是存在于Action类中的函数,就像Smarty,ThinkPHP 的Action相当于smarty中的实例化的$smarty类.如果未指定display页面,则会默认寻找tpl/Form/show.html


(二).      访问:http://localhost:1243/think/index.php/Form/add     新增数据到数据库中

  代码如下:

//添加数据
	public function add(){
	     // $model=D("Form");
	    $user=M("user");
            //验证规则可以写在action中
            $validate = array(
                array('name','require','用户名不能为空'), // 为空验证
                array('name','','用户名已存在','1','unique','1'),
                array('mail','email','邮箱格式错误'),
            );
            //将规则写入model
            $user->setProperty("_validate",$validate);
			if(!isset($_POST['sub'])){
				$this->display();
				exit;
			}
			//表单提交
  	    //unset($_POST['sub']);
            //create函数其实是对数据库进行一次验证,在数组里面有的列才会存在在create所返回的数组中,所以可以省去unset操作
            //例如在数据库表中,不存在列 mail,但是表单提交上来的有mail,create进行验证后返回的数组中不会包含mail
            $res=$user->create();
            if(!$res){
               //错误提示
               $error=$user->getError();
               $this->assign("error",$error); 
               $this->display();
               exit;       
            }		
			$result=$user->add();
			if($result>0){
				$this->success("添加成功","__URL__/show");
			}else{
				$this->error("添加失败,请重试");
			}
		
		}

(1). D()函数在3.1以后无法进行单独的表设置,如果在Model文件夹下定义了一个FormModel.class.php,再用D("Form")实例化该Model,会提示数据表 Form不存在

暂未找到方法,请大家赐教

(2).进行自动验证的时候,可以将验证的规则写在action中,如上代码

     倘若非要写在一个自定义的Model中,则如下

 protected $_validate=array(
    //验证规则可以写在action中
            array('name','require','用户名不能为空'), // 为空验证
            array('name','','用户名已存在','1','unique','1'),
            array('mail','email','邮箱格式错误'),
    );

    (3).关于create函数和add函数,见如上程序代码中注释


      欢迎提出问题,共同解决。

           

www.phpzy.comtrue/phprm/5351.htmlTechArticleThinkPHP学习笔记1-CURD ThinkPHP学习笔记1-----CURD ThinkPHP为我们提供非常快捷的方法执行curd操作,怎么用还是看手册,这里主要写一点我自己经验 例如 (一) 访问:http://localhost:1243/think/i...

相关文章

相关频道:

PHP之友评论

今天推荐