<?php include_once("../phpFiles/connMysql.php");//包含连接数据库的代码 $queryType=$_POST['queryType'];//目标数据表 $queryKeywords=$_POST['queryKeywords']; //查询词 $queryKeywords = preg_replace('#\s+#', ' ',$queryKeywords);//将字符串中多个连续空格替换为一个空格 $keywords=explode(" ",$queryKeywords); //查询词按空格分割 //根据不同的数据表生成不同的查询语句 if($queryType=="users") { $sqlsmt="select email,truename,enName,stuid,degree,supervisorname,tel,room from $queryType where "; //查询语句的初始值 //利用循环 生成对每个关键词的查询语句 foreach ($keywords as $keyword) { $sqlsmt.="concat(email,truename,enName,stuid,degree,supervisorname,tel,room) like '%$keyword%' or ";//本句是关键,利用concat函数实现从多个字段查询单个关键词,并用' or '关键词把每个关键词的concat结果合并 } $sqlsmt=substr($sqlsmt,0,strlen($sqlsmt)-3); //去掉查询字符串尾部的' or ' $sqlsmt.=" order by degree asc, stuid desc"; //追加排序子句 } else if($queryType=="papers") { $sqlsmt="select authors,title,jorc,vap,level,status from $queryType where "; foreach ($keywords as $keyword) { $sqlsmt.="concat(authors,title,jorc,vap,level,status) like '%$keyword%' or "; } $sqlsmt=substr($sqlsmt,0,strlen($sqlsmt)-3); $sqlsmt.=" order by level desc, vap desc"; } else if($queryType=="softwares") { $sqlsmt="select authors,title,num,date from $queryType where "; foreach ($keywords as $keyword) { $sqlsmt.="concat(authors,title,num,date) like '%$keyword%' or "; } $sqlsmt=substr($sqlsmt,0,strlen($sqlsmt)-3); $sqlsmt.=" order by date desc"; } else if($queryType=="patents") { $sqlsmt="select authors,title,acceptDate,acceptNum,authorizeDate,authorizeNum from $queryType where "; foreach ($keywords as $keyword) { $sqlsmt.="concat(authors,title,acceptDate,acceptNum,authorizeDate,authorizeNum) like '%$keyword%' or "; } $sqlsmt=substr($sqlsmt,0,strlen($sqlsmt)-3); $sqlsmt.=" order by acceptDate desc"; } $myrs=mysql_query($sqlsmt);//执行查询 if(mysql_num_rows($myrs)==0)//如果结果为空 返回'no' { echo(json_encode("no")); } else //否则返回json格式的结果 { while($row=mysql_fetch_array($myrs)) { $temp[]=$row; } echo(json_encode($temp)); } ?>
运行结果截图:
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP+ajax技巧与应用小结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》