Forum Moderators: coopster

Message Too Old, No Replies

Checkboxes, Arrays and SQL

Allowing users to choose which fields of a database they can search.

         

Maynard

2:25 pm on Jun 9, 2004 (gmt 0)

10+ Year Member



I am very new with PHP, so I hope someone can help me: With the help of JPJones, I've managed to write a basic search script querying a MySQL database.

I would like my users to choose which fields they search from, eg search for "red" in field1, field2 and field7 only.

I would use checkboxes for this, using [], eg:
<input type="checkbox" id="field[]" value="field1">Field 1

I understand I would have to split the $field array (on the comma delimiter?) and then use it in my SQL statement. Would it be something like this?

foreach($fieldarray as $key=>$value)
{
$sql = "SELECT * FROM table WHERE $fieldarray[i] LIKE '%$searchword%'";
}

I have no idea of the correct syntax.

I hope someone can help.

Thanks,
Maynard.

DevlshOne

6:31 pm on Jun 9, 2004 (gmt 0)

10+ Year Member



If I read this correctly, you have a list of fields that can be selected via checkboxes and you want to iterate through only the selected fields for your query?

If this is right, try something like this..

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

Maynard

7:37 am on Jun 10, 2004 (gmt 0)

10+ Year Member



Thanks, DevLshOne. I will try it today and let you know!

hephaistos

8:15 am on Jun 10, 2004 (gmt 0)

10+ Year Member



hello,

well with this solution you will make N sql queries...

I think you will add the checked field to your query like this:

$query = "SELECT * FROM table WHERE ";
foreach($fieldarray as $key=>$value)
{
$query .= $key." LIKE '%".$value."%' AND ";
}
$query = substr($query,0,-4); //kill last AND
echo $query;

hope this helps :)

regards