在对数据进行更新、删除、查询时经常需要设置 sql 命令的条件,phpGrace 数据库操作类提供了条件相关的函数可以方便的完成 sql 命令的条件设置。
功能 :设置条件(只使用 此函数 就可以完成全部条件设置 )。
参数 :
1 sql 命令的条件部分,使用 ? 作为预处理占位符,如 : (a = ? and b > ?) or c < ?
2 对应占位符的数组数据,可选参数,默认 null
1 where() 在一次数据操作时只能使用一次,多次使用会覆盖前面的 where() 设置; 2 可以使用 where() 作为 and() 和 or() 2个函数的基础; 3 只使用 where() 就可以设置全部条件 where(条件1 = ? and 条件2 > ? or ... and ...),提供 and() 和 or() 是为了简化复杂条件的设置过程,提高代码可读性。
功能 :添加 and 条件
参数 :
1 sql 命令的 and 条件部分,使用 ? 作为预处理占位符,如 : (a = ? and b > ?) or c < ?
2 对应占位符的数组数据,可选参数,默认 null
功能 :添加 or 条件
参数 :
1 sql 命令的 or 条件部分,使用 ? 作为预处理占位符,如 : (a = ? and b > ?) or c < ?
2 对应占位符的数组数据,可选参数,默认 null
// 例1 全部使用 where 设置条件 $res = database::table('students') ->where('st_id > ? and st_name like ? ', array(2, '%grace%')) ->delete(); // 运行时 sql // delete from grace_students where ( st_id > ? and st_name like ? ); // 例2 使用 and $res = database::table('students') ->where('st_id > ?', array(2)) ->and('st_name like ?', array('hai') ) ->and('st_class_id = ?', array(1)) ->delete(); // 运行时 sql // delete from grace_students where ( st_id > ? ) and ( st_name like ? ) and ( st_class_id = ? ); // 例3 使用 or $res = database::table('students') ->where('st_id > ?', array(2)) ->or('st_name like ?', array('hai') ) ->or('st_class_id = ?', array(1)) ->delete(); // 运行时 sql // delete from grace_students where ( st_id > ? ) or ( st_name like ? ) or ( st_class_id = ? ); // 例4 组合模式 $res = database::table('students') ->where('st_id > ?', array(2)) ->and('st_name like ?', array('hai') ) ->or('st_class_id = ?', array(1)) ->delete(); // 运行时 sql // delete from grace_students where ( st_id > ? ) and ( st_name like ? ) or ( st_class_id = ? ); // 例5 不使用 where() 基础函数 $res = database::table('students') ->and('st_id > ?', array(2200000)) ->and('st_id < ?', array(2417085)) ->delete(); // 运行时 sql // delete from grace_students where ( st_id > ? ) and (st_id < ? );
在实际项目开发过程中我们经常会动态地组合查询条件,您可通过多次调用 and() 或者 or() 方法来实现。
注意 :
此演示仅用于演示动态条件,实际运行效率极低,不推荐开发者学习和使用此处产生的 sql 命令。
<?php namespace grace\controller; use grace\grace; use grace\database; class index extends grace{ public function index(){ // 利用 url 参数实现动态条件 // 如 : http://localhost/index/index/min/2200000/max/2300000/kwd/grace // url 的参数动态出现或者不出现 $table = database::table('students'); // 下面的代码会根据 url 参数实际情况动态产生条件 if(!empty($_GET['min'])){ $table->and('st_id >= ?', array($_GET['min'])); } if(!empty($_GET['max'])){ $table->and('st_id <= ?', array($_GET['max'])); } if(!empty($_GET['kwd'])){ // 假设 $_GET['kwd'] 触发多个 like 条件 $table->or('st_name like ?', array('%'.$_GET['kwd'].'%')); $table->or('st_add_time like ?', array('%'.$_GET['kwd'].'%')); // 上面的语法还可以这样写 //$table->or('st_name like ? or st_add_time like ?', array('%'.$_GET['kwd'].'%', '%'.$_GET['kwd'].'%')); } $table->delete(); // 可以通过调试控制台观察获取最终执行的 sql 命令 // 代码方式 echo $table->getSql(); } }
通过上面的例子您可以发现通过 $table->and() 或者 $table->or() 可以动态追加条件,如果您的条件是一个整理好的数组,那么也可以通过数组的遍历,在循环内部动态地设置条件;