Brian
Brian

Reputation: 365

php/mysql show data from chosen checkboxes

I have a table called FRUIT

id  type    daysold
1   banana  5
2   apple   6
3   apple   4
4   peach   2
5   banana  6

What I would like is to have 3 checkboxes:
Banana [ ]
Apple [ ]
Peach [ ]
SUBMIT

Then if I've only checked "Banana" and "Peach" the mysql output should only show me the rows that matches those two types. And the checkboxes should remain checked to highlight what was chosen.

I can make the checkboxes but then that's about it really. I don't know how to properly get the info from the checkboxes and down to the WHERE argument in the MYSQL-code. Especially not with two types chosen.

If it was just a dropdown menu with a single choice then I'd add the choice to the url and put WHERE type='$choice' - but I'm struggling with the multiple choices.

I'm a bit of a novice at both php and mysql, so I'm a bit lost on this one.

Upvotes: 1

Views: 1473

Answers (1)

Davide Gualano
Davide Gualano

Reputation: 13003

I'd make a form like this:

<form action="processingPage.php" method="post" name="nameHere">
    <input type="checkbox" name="fruit[]" value="Banana" /> Banana<br />
    <input type="checkbox" name="fruit[]" value="Apple" /> Apple<br />
    <input type="checkbox" name="fruit[]" value="Peach" /> Peach<br />
    <input type="submit" value="Submit" /> 
</form>

In processingPage.php:

<?php
$fruits = array();
foreach($_POST['fruit'] as $fruit) {
    $fruit = mysql_real_escape_string($fruit);
    $fruits[] = "'{$fruit}'"; 
}

$sql = "select * from fruit where type in (" . implode(", ", $fruits) . ")";
//execute query and retrieve results
?>

Upvotes: 1

Related Questions