1. 程式人生 > >ThinkPHP框架五對資料的操作和條件查詢

ThinkPHP框架五對資料的操作和條件查詢

條件查詢

//查詢主鍵為2的記錄
		//$list = M('goods')->select(2);
		//批量查詢這些主鍵
		//$list = M('goods')->select("1,2,3,4,5,6,9");
		//where條件查詢
		//$list = M('goods')->where("goods_price > 2000 and goods_name like '%諾基亞%'")->select();
		//limit
		//$list = M('goods')->limit(5)->select();//相當於limit(0,5) 第一個引數是從 哪裡開始第二個引數是獲取多少條
		//where 和 limit
		// $list = M('goods')->where('goods_price > 2000')->limit(3)->select();
		//排序
		// $list = M('goods')->order('goods_price desc')->select();  //預設是升序  desc是降序

		//查詢指定欄位
		// $list = M('goods')->field('goods_name,goods_price')->select();
		//having
		// $list = M('goods')->having('goods_price>4000')->select();
		$list = D('goods')->group('goods_brand_id')->field('goods_brand_id,max(goods_price) as m')
		->limit(3)->having('m>2000')->select();
		$this->assign("list",$list);

having和where的區別 區別一: where後面跟的欄位必須在資料表中有 select goods_name,goods_price from goods where goods_weight>100;  這樣用where是對的 select後面的紅色的就是資料集 where後面不必資料集中有資料表中有就可以having必須是資料集中有 區別二: 是在分組的時候必須使用having

select * from 表  where 條件  group by 分組  having 條件


動態查詢

getby+欄位名

聚合函式


資料新增

1、通過關聯陣列的方式新增
public function test2(){
		$data = array(
			'goods_name'=>'dashouji',
			'goods_price'=>'343'
		);
		echo M('goods')->add($data);
	}

2、通過AR(Acion record)方式新增
ublic function test3(){
		$data=M('goods');
		$data->goods_name = 'shoujishi';
		$data->goods_price = 090;
		$data->add();
	}

資料修改

1、通過關聯陣列方式新增
public function test4(){
		$data = array(
			'goods_price'=>121,
			'goods_name'=>'shouji233',
			'goods_id' => 141
		);
		echo M('goods')->save($data);  //返回受影響的記錄條數
	}

2‘通過AR(Action Record)方式新增
public function test5(){
		$data = M('goods');
		$data->goods_name = "sds";
		$data->goods_id=150;
		echo $data->save();
	}


資料刪除

刪除欄位的四種方式
public function test6(){
		// echo M('goods')->delete(141);
		//echo M('goods')->delete("150,151");
		// echo M('goods')->where("goods_name = 'apple'")->delete();
		$model = M('goods');
		$model->goods_id = 138;
		echo $model->delete();
	}
}


直接執行SQL語句

public function test7(){
		//查詢的時候使用 query
		// $list = M()->query('SELECT * FROM SW_GOODS');
		//增刪改用execute方法
		$list = M()->execute('DELETE FROM SW_GOODS WHERE GOODS_ID = 133');
		var_dump($list);
	}