background image

PHP 多关键字、多字段生成 SQL 语句的函数

本文分享一个

php 自定义函数,实现多关键字、多字段生成 sql 查询语句的方法,在多条件

查询的环境中用的比较多。

例子:
代码示例

:

$keyword="1 2 3";
echo  $sql=search($keyword,"enter_gongyin_pic","a+b+c");  // 函 数 生 成 , 没 有 LIMIT, 没 有
ORDER BY 

生成

sql 语句:

代码示例

:

SELECT  *  FROM  `enter_gongyin_pic`  WHERE  `a`  LIKE  '%1%'  OR  `a`  LIKE  '%2%'  OR  `a` 
LIKE '%3%' OR `b` LIKE '%1%' OR `b` LIKE '%2%' OR `b` LIKE '%3%' OR `c` LIKE '%1%' 
OR `c` LIKE '%2%' OR `c` LIKE '%3%'
$keyword 由 POST 或者 GET 获得,按空格分开,可以多字段去查找.
多关键字、多字段生成

sql 查询语句的函数:

<?php
/**
* 查询条件构造语句
* edit: www.jbxue.com
*/
function search($keyword,$table,$field) 

/**
//形参说明: 
//keyword 为关键字,如“北京首都 方向 火车”。带有空格或者不带 
//table 为表名,如 enter_gongyin_pic。 
//field 为字段组合,如查找一个字段就写好 name  
//如查找两个以上就用 name+picdir 
*/
//首先确定 field 
$new_field=explode()("+",$field); //按+剥离 
$field_count=count($new_field); //得到的结果数量 
 
 
$newstring=explode(" ",$keyword); //按空格剥离 
$newstring2=array(); 
   //把字符串去掉没有用的空格叔祖元素 
   $i=0; 
   foreach ($newstring as $key => $value) { 
   if($value!="") 
   {