Forum Moderators: coopster

Message Too Old, No Replies

Nesting For Each... and While statements

PHP and SQL

         

Maynard

2:06 pm on Jun 10, 2004 (gmt 0)

10+ Year Member



Is it possible to nest For Each and While statements? I have the following code to enable users to search the entire database:

===========================
$searcharray = Array();
$searcharray = explode(" ",$searchword);

$sql = "SELECT * FROM table WHERE 1=1 ";

reset($searcharray);

while (list($key,$val) = each($searcharray))
{
$sql .= " AND (field1 LIKE '%$val%' OR field2 LIKE '%$val%' OR field3 LIKE '%$val%' OR field4 LIKE '%$val%')";
}

$result = mysql_query($sql,$db);
===========================

But I also want to give users the option to choose which fields to search on (via checkboxes). Here is the code:

===========================
foreach($field as $key => $col_value)
{
$sql = "SELECT * FROM table WHERE '$key' LIKE '%$searchword%'";
}
===========================

How would I integrate the two?

I'm a complete PHP (but not coding) newbie.

Mank thanks,
Maynard.

dcrombie

3:31 pm on Jun 10, 2004 (gmt 0)



Perhaps this will help;

$where = array();
$where[] = "field1='val1';
$where[] = "field2='val2';

$query = "SELECT * FROM table";
if($where) $query .= " WHERE " . implode(" AND ", $where);
$query .= " ORDER BY field";

;)

Maynard

9:12 am on Jun 14, 2004 (gmt 0)

10+ Year Member



Thanks! But I'm not sure I understand what your code is doing. Could you, if you have time, go through it line by line?

Many thanks.