Reply to Re: Need help with multiple criteria query

Your name:

Reply:


Posted by C. David Rossen on 11/14/05 17:53

Hi Mike:

Thank you very much for the help. I haven't tried this yet, but I have a
couple of questions before I test it out.

1. In the array, do I need to use all the fields in the table or just the
ones that are contained in the form used for the search?

2. Where you have $fields['Field1'] = "Lions";, etc, etc... would I
substitute that with:
$Field1=$_POST['Field1'];, etc, etc, ?

3. What is sprintf? Is that a built in function or something?

Thanks again, I look forward to trying this out.

David

"Mike Gatny" <mgatny@gmail.com> wrote in message
news:1131953440.445922.103450@f14g2000cwb.googlegroups.com...
> How about something like this?
>
> //[CODE]
> <?php
> // array using all possible search fields as keys, initialized to null
> $fields = array(
> "Field1" => null,
> "Field2" => null,
> "Field3" => null,
> "Field4" => null,
> "Field5" => null,
> "Field6" => null,
> "Field7" => null,
> "Field8" => null,
> "Field9" => null,
> "Field10" => null
> );
>
> // based on user input, populate the $fields array, for example:
> $fields['Field1'] = "Lions";
> $fields['Field2'] = "Pistons";
> $fields['Field3'] = "Red Wings";
> $fields['Field4'] = "Tigers";
> $fields['Field5'] = "Wolverines";
> // ... and let's pretend the rest are not specified by the user
>
> // add a piece to the WHERE clause if the field has a value
> $where_pieces = array();
> $message_pieces = array();
> $where_format = "%s LIKE '%%%s%%'";
> $message_format = "%s = '%s'";
> foreach($fields as $field => $value) {
> if(!is_null($value)) { // ignore if field was not specified
> $where_pieces[] = sprintf($where_format, $field,
> $value);
> $message_pieces[] = sprintf($message_format, $field,
> $value);
> }
> }
>
> // join the pieces of the clause and message together
> $where = ' WHERE ' . implode(' AND ', $where_pieces);
> $message = 'Results for ' . implode(', ', $message_pieces);
>
> // start building our query, and add our WHERE clause
> $sql = "SELECT * FROM tablename ";
> if(!empty($where_pieces)) {
> $sql .= $where;
> }
>
> // add on some more
> $sql .= " ORDER BY LastName ASC ";
>
> // execute the query
> $result = mysql_query($sql);
> print "$message\n";
>
> // display results here...
> ?>
> //[/CODE]
>

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация