English 中文(简体)
将自定义查询转换为SQL
原标题:Converting custom queries into SQL
  • 时间:2011-02-07 10:14:13
  •  标签:
  • php
  • sql
  • mysql

使用PHP将以下输入转换为SQL的最佳方式是什么?

+a - includes a
+(cd) - includes c or d but not both
+(c/d/e) - includes any of these
-f - does not include f

我曾使用preg_replace或爆炸来循环执行和do-if语句,但没有任何东西能始终如一地工作。

我基本上需要像

+a +(c/d/e)

进入

SELECT * FROM the_table 
WHERE description LIKE "%a%" 
AND (description LIKE "%c%" OR description like "%d%" OR description LIKE "%$e%")

谢谢

更新:

这是我的尝试。我相信有一个更简单的方法。。。

public function custom_query($query){

    $fields = " feed_items.description ";

    $return_query = "";

    $query = str_replace(" ",   , $query);

    $pluses = explode( + ,$query);

    foreach($pluses as $plus){

            $plus = trim($plus);

            if (substr($plus,0,1) ==  ( ){
                $return_query .=  AND ( ;

                $plus = str_replace(array( ( , ) ),   , $plus);

                $ors = explode( / , $plus);

                foreach($ors as $or){
                    if ($or){
                        $return_query .= $fields." LIKE  %".$or."%  OR";
                    }
                }

                $return_query = rtrim($return_query,   OR );
                $return_query .=   ) ;
            } else {
                if ($plus){
                    $return_query .=   AND   . $fields.  LIKE  . "% .$plus. %" ;
                }
            }

        }

    $negatives = explode( - ,$query);

    foreach($negatives as $negative){

            $negative = trim($negative);

            if (substr($negative,0,1) ==  ( ){
                $return_query .=  AND ( ;

                $negative = str_replace(array( ( , ) ),   , $negative);

                $ors = explode( \ , $negative);

                foreach($ors as $or){
                    if ($or){
                        $return_query .= $fields." NOT LIKE  %".$or."%  OR";
                    }
                }

                $return_query = rtrim($return_query,   OR );
                $return_query .=   ) ;
            } else {
                if ($negative){
                    $return_query .=   AND   . $fields.  NOT LIKE  . "% .$negative. %" ;
                }
            }

        }

    $return_query =   AND  .ltrim($return_query,   AND  );

    return $return_query;

}
问题回答

因为你不需要嵌套表达式。它很简单,regex实际上只是懒惰:

$sql = preg_replace_callback(" 
           ([+-])            # AND or NOT
           (w+              # capture a single word
           | (              # or something enclosed in literal braces
                (w+         # word
                  ([/\\])?    # logical delimiter
                [^)]*)       # remainder words and/or delimiters
             )
           ) x",
       "to_sql", $search_pattern);

function to_sql($match) {
    @list($uu, $logical, $word, $words, $or) = $match;

    if ($logical == "+") {
        $sql = " AND (";
    }
    else {
        $sql = " OR (";
    }

    if ($words) {
        $words = explode($or, $words);
    }
    else {
        $words = array($word);
        $or = "/";
    }

    foreach ($words as $i=>$word) {
        $words[$i] = "description LIKE  %$word% ";
    }

    $or = ($or == "/") ? " OR " : " XOR ";
    $sql .= implode($or, $words);

    return "$sql)";
}

它将返回以“AND”开头的语句,这是可以调整的,但更容易作弊,只需在前面加上“TRUE”即可将其转换为有效的WHERE子句。

$pattern = "+a +(c/d/e)";

// replace a, c, d, e with "description like "%something%"
$pattern = preg_replace( #[^()+\-\\/s]# ,  description like "%$0%" , $pattern);

// replace operators
$replacements = array(
     +   =>   and  ,
     -   =>   and not  ,
     \  =>   xor  ,
     /   =>   or  ,
);
$pattern = str_replace(array_keys($replacements), $replacements, $pattern);
$pattern = trim($pattern);

// remove first "and"
// * "and something and something_else" becomes "something and something_else"
// * "and not something and something_else" becomes "not something and something else"
$pattern = preg_replace( #^and # ,   , $pattern);

Patten应该以+-开头,或者不使用任何运算符。

不确定是否将替换为xor-取决于您希望如何处理(a c)[cd]等。





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签