Re: elegant way of doing something else the last time through a loop?
| From: | Paul Chvostek | Date: | Tue, 15 Jul 2003 15:13:44 +0000 |
| Subject: | Re: elegant way of doing something else the last time through a loop? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-155290@lists.php.net to get a copy of this message | ||
On Mon, Jul 14, 2003 at 01:11:11PM +0200, Petre Agenbag wrote:
>
> HI list
Hi Petre.
> I want to search through a table by "exploding" the search string and
> then compounding my own sql string by working through the array.
I do alot of this. I have a solution which offloads the slight extra
CPU onto the database server, while simplifying the PHP code a little.
> the if statement inside the loop is
> meant to "strip" out "the" and "and", meaning that it won't
> much help to
> use that approach anyway.
I've got a more flexible way of doing that too. How about this:
$sql = "SELECT * FROM $table_name WHERE ";
if ($_POST['any_all'] == 'ANY') {
$logic = 'OR';
$sql .= '1=0';
}
elseif ($_POST['any_all'] == 'ALL') {
$logic = 'AND';
$sql .= '1=1';
}
else
die ('form hacking detected');
// protect from nasty user input
$string = ereg_replace( '[^a-z0-9]+', ' ',
strtolower($_POST['text']) );
$skip = array(
'the' => 1,
'and' => 1,
'a' => 1,
);
foreach (explode(' ', $string) as $val) {
if (!$skip[$val]) {
$sql .= $logic . " name like '%$val%'";
}
}
$sql .= ' ORDER BY name';
--
Paul Chvostek <paul@it.ca>
it.canada http://www.it.ca/
Free PHP web hosting! http://www.it.ca/web/