|
Posted by luke on 07/26/05 03:26
Hi
If the question is how can you build an SQL query that tests a variable
amount of LIKE conditions .. then I've used this strategy before. Possibly
not the best solution and/or could do with some tidying by a better coder.
Change the following:
> $A=$_POST['A'];
> $u=$_POST['u'];
> $B=$_POST['B'];
> $w=$_POST['w'];
> $C=$_POST['C'];
> $x=$_POST['x'];
> $D=$_POST['D'];
> $y=$_POST['y'];
> $E=$_POST['E'];
> $z=$_POST['z'];
Into this:
$A="OR symb LIKE . "$_POST['A'];
$u="OR symb LIKE . "$_POST['u'];
$B="OR symb LIKE . "$_POST['B'];
and so on for the remaining variables. This is building snippets of SQL.
Because you want the _first_ SQL snippet to _not_ begin with 'OR' (but all
preceding snippets to) .. I'd write a switch, and list your variables in the
exact order that you did above. This switch code will take out the three
character 'OR ' from the beginning of first variable that has been assigned
something.
switch (TRUE) {
case $A:
$A = substr($A, 3);
break;
case $u:
$u= substr($u, 3);
break;
case $B:
$B= substr($B, 3);
break;
}
Add another 'case' for every remaining variable, following the same format.
Then your SQL query will look like this
$query ="SELECT matom,nazwa FROM chem WHERE $A $u $B";
Add the remainging variables in the same order as you have listed them
before, one after the other with spaces in between. Where a value for a
variable doesn't exist, it will simply be nothing, i.e., not part of the
query. The first variable will have its 'OR ' removed.
Um .. I hope this works anyway :>
Ka Kite
Luke
"Konrad Tuszkowski" <konrad.t@op.pl> wrote in message
news:dc3adn$8i7$1@news.onet.pl...
> hello
> i have a form with 5 fields. and my problem is that if user put 2 or more
> same variables my script finds in db only 1 and i need to search all
> variables in db even if they r same.
>
> <http>
> <body>
> <?php
> $A=$_POST['A'];
> $u=$_POST['u'];
> $B=$_POST['B'];
> $w=$_POST['w'];
> $C=$_POST['C'];
> $x=$_POST['x'];
> $D=$_POST['D'];
> $y=$_POST['y'];
> $E=$_POST['E'];
> $z=$_POST['z'];
> require("connect.php");
> $query ="SELECT matom,nazwa FROM chem WHERE symb LIKE '$A' OR symb LIKE
'$B'
> OR symb LIKE
>
> '$C' OR symb LIKE '$D' OR symb LIKE '$E'";
> $result = mysql_query ($query) or die ("Zapytanie zakonczone
> niepowodzeniem");
> $wiersze=mysql_num_rows($result);
> echo"<br>$wiersze";
> for ($i=0;$i<$wiersze;$i++) {
> $wiersz = mysql_fetch_array($result);
> $a=$wiersz["matom"];
> $b=$wiersz["nazwa"];
> $tab_b[]=$b;
> $tab_a[]=$a;
> echo "Masa molowa <b>$b"."u</b> wynosi $a<br>";
> }
> if(!$u)
> $u=1;
> if(!$w)
> $w=1;
> if(!$x)
> $x=1;
> if(!$y)
> $y=1;
> if(!$z)
> $z=1;
>
>
$M=($tab_a[0]*$u)+($tab_a[1]*$w)+($tab_a[2]*$x)+($tab_a[3]*$y)+($tab_a[4]*$z
> );
> echo "<br>".$M;
> mysql_free_result($result);
> mysql_close($link);
> ?>
>
>
>
> regards
>
>
>
>
Navigation:
[Reply to this message]
|