说白了,其实就是字符串的游戏。拼拼凑凑而已。这里使用数组储存条件和查询语句,程序也不长,有详细的注释,不会化您多少功夫的。呵呵。
在conditions_search.html中输入您的查询条件,点击查询。您输入的条件在提交到display_search_SQL.php进行处理后,将给出合适的SQL语句。
/***************conditions_search.html****************/
<html>
<head>
<title>Conditions_Search多条件查询</title>
</head> www.444p.com
<body>
Conditions_Search多条件查询:
<form name="form1" method="post" action="display_search_SQL.php">
Condition1:<input type="text" name="condition1"><br>
Condition2:<input type="text" name="condition2"><br>
Condition3:<input type="text" name="condition3"><br>
Condition4:<select name="condition4">
<option value='' selected>all</option>
<option value='red'>red</option>
</select><br>
<input type='submit' name='search' value='查询'>
</form>
</body>
</html>
/***************conditions_search.html**********************/
/***************display_search_SQL.php*********************/
<?//从conditions_search.html接收到四个条件,
//condition1,condition2,condition3,condition4。
www.444p.com
//其中有文本框输入的字符串,有列表框下拉选择的,
//这些接收条件的方式都不重要。
//条件还可以增加(没什么限制,当然也不要太大,超过数组的上限)。
//以下有几点注意:
//认为条件值为空时,不限制;
//要查询的表名为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语句,下面再根据情况处理。(数组很容易扩充) php学习之家
for($i=0;$i<$ConditionsNumber;$i++)
{
if($ConditionsArray[$i]=="")
$SearchSQLArray[$i]="";
//第一步处理:如果条件值为空,相应的SQL语句为空。
$haveWhere=false; //设“存在where”检查标志的初值为false。
for($j=0;$j<$i;$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<$ConditionsNumber;$i++)
$sql=$sql.$SearchSQLArray[$i];
$sql="select * from mytable".$sql.";";
//组成SQL语句
echo $sql;
?>
/**************display_search_SQL.php*********************/
摘自:<a href=http://phpuser.com/tips_and_tricks/detail.php?id=126>PHP中文用户</a>

















最新评论(共有 1 条评论)更多评论...
游客: v的评论 (2008-06-13 14:57 pm)