您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

多条件查询_MySQL

2026/1/11 22:10:47发布12次查看
有关多条件查询的问题,以前我在论坛发过帖子,前几天有网友对此感兴趣,我就花了点时间整理了一下,其实并没有什么特别的,关键在于写出正确的sql查询语句,由于各人所用数据库不同,而sql语句是相同的。所以在此我仅给出根据多个条件自动生成的符合要求的sql语句。对条件的数目基本没有限制,不超过数组的组元数目就可以了。
说白了,其实就是字符串的游戏。拼拼凑凑而已。这里使用数组储存条件和查询语句,程序也不长,有详细的注释,不会化您多少功夫的。呵呵。
在conditions_search.html中输入您的查询条件,点击查询。您输入的条件在提交到display_search_sql.php进行处理后,将给出合适的sql语句。
/***************conditions_search.html****************/
conditions_search多条件查询
conditions_search多条件查询:
condition1:
condition2:
condition3:
condition4:
all
red
/***************conditions_search.html**********************/
/***************display_search_sql.php*********************/
//从conditions_search.html接收到四个条件,
//condition1,condition2,condition3,condition4。
//其中有文本框输入的字符串,有列表框下拉选择的,
//这些接收条件的方式都不重要。
//条件还可以增加(没什么限制,当然也不要太大,超过数组的上限)。
//以下有几点注意:
//认为条件值为空时,不限制;
//要查询的表名为testtable;
//condition1对应的字段名为column1……
//
$conditionsnumber=4; //共有4个条件。(可改为实际使用的条件数)
$conditionsarray=array($condition1,$condition2,$condition3,$condition4);
//把各个条件排入一个数组中,方便下面循环。(数组很容易扩充)
$searchsqlarray=array( where column1='$condition1', where column2 like '%$condition2%', where column3='$condition3', where column4='$condition4');
//预写好一些sql语句,下面再根据情况处理。(数组很容易扩充)
for($i=0;$i{
if($conditionsarray[$i]==)
$searchsqlarray[$i]=;
//第一步处理:如果条件值为空,相应的sql语句为空。
$havewhere=false; //设“存在where”检查标志的初值为false。
for($j=0;$j//从开始到目前循环的i,处理有哪些where
//需要变为and。
{
$whereposition=strpos($searchsqlarray[$j],where);
//检查i前面是否有where出现。
if(($whereposition==1)&&($havewhere==false))
{
$searchsqlarray[$i]=ereg_replace(where,and,$searchsqlarray[$i]);
//where的位置为1,且前面已有where。
//则where换成and。
$havewhere=true; //存在where”检查标志设为true。
}
}
};
for($i=0;$i$sql=$sql.$searchsqlarray[$i];
$sql=select * from mytable.$sql.;;
//组成sql语句
echo $sql;
?>
/**************display_search_sql.php*********************/
摘自:php中文用户
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product