views:

89

answers:

2

HELLO

SORRY FOR FRENCH , i will try english i have tree arrays like this

$keys = array("elment1","elment1","elment2","elment1");
// this one can have duplicates values , 

$operator = array("=","<",">","=");
// operators for Mysql query 

$queries = array("query1","query2","query3","query4");
// mixtes values

the question is :

how can i combine this tree arrays like so :

$string = "SELECT FROM tables 
           WHERE
           (elment1 = query1 OR elment1<query2 OR elment1=query4)
           // need group duplicates keys 
           AND
           elment2 > query3";
           // non duplicates 

why i'm asking that , because i need this for a multi queries filtres

the user push a (+) button to add keys+operator+query a many time as he like

i'm using jquery to create form elements , and a each() function to generate 3 arrays before posting all to php

if someone know a best approach then welcome and thank you very much

+2  A: 

You asked a question in French, I'll answer in English and you can use Google Translate if you need a translation. [Utilisez Google Translate pour traduire cette réponse si vous voulez.]

First of all, you'll need to concatenate the pieces. Pay attention to the mysql_real_escape_string, which makes the whole operation a little bit safer.

$joined = array();
for($i = 0, $size = sizeof($keys); $i < $size; ++$i) {
    $joined[$i] = $keys[$i] . " " . $operator[$i] . " '" . mysql_real_escape_string($queries[$i]) . "'";
}

Then you can use implode:

$string = 'SELECT [...] WHERE (' . implode(' OR ', $joined) . ')';
MvanGeest
thanx for your response and sorry for my french your code is very handy , but this will add OR for all keys i want do that for duplicates keys only and by default use AND for non duplicates ones:$string = "SELECT FROM tables WHERE (elment1 = query1 OR elment1<query2 OR elment1=query4) // if i have other duplicates it will be AND (KEY1 = query OR KEY2=QUERY) AND elment2 > query3";
cranberies
+1  A: 

Bonjour,

Here is the code. tried and tested. Voila le code... essayer avec succé

$keys = array("elment1","elment1","elment2","elment1");
// this one can have duplicates values , 
$operator = array("=","<",">","=");
// operators for Mysql query 
$queries = array("query1","query2","query3","query4");
// mixtes values

$joined = array();
for($i = 0, $size = sizeof($keys); $i < $size; ++$i)
{
    $joined[$keys[$i]][] = $keys[$i] . $operator[$i] . $queries[$i];
}

foreach ($joined as $key => &$value)
{
    $value = implode(' OR ', $value);
    $value = "(" . $value . ")";
}
$query = implode(' AND ', $joined);
print $query;
Anand
Anand
use 'view source' to view the actual output.. the '<' and '>' signs hide the string in the browser
Anand
thank you so much Anand , this work perfectly i've tested with random arrays , it's just works thanks
cranberies
finally i've integrate your code in my application , thanksit works like i excepted , nice work
cranberies