searching multiple data with checkbox
I have a database with a table a bank, there are 3 fields in that ta开发者_运维技巧ble is id, bank_name, branch_bank. I want to search databased on using the checkbox bank_name .
There are 3 records bank_name with 3 checkboxes are: Bank1, Bank2, Bank3
.
How to make it?
first of all, you'll need some form, preferably built by php itself, since you use values stored in the dbrms.
<form method="post">
<label for="banking_bank1">Bank1:</label>
<input id="banking_bank1" type="checkbox" name="banking[]" value="bank1" /><br />
<label for="banking_bank2">Bank2:</label>
<input id="banking_bank2" type="checkbox" name="banking[]" value="bank2" /><br />
<label for="banking_bank3">Bank3:</label>
<input id="banking_bank3" type="checkbox" name="banking[]" value="bank3" /><br />
<button type="submit" name="search" value="search">Search</button>
</form>
This will build an array for php, which includes all bank names selected.
You didn't specify which dbrms you're using, I picked mysql, the structure will be the same for others.
if ( isset($_POST) && isset($_POST['search']) )
{
$banksWhereClause = '';
if ( ! empty($_POST['banking']) ) // if the banking var is set, we'll add the values to the query
{
$banksToSearch = is_array($_POST['banking']) ? $_POST['banking'] : array($_POST['banking']);
foreach ( $banksToSearch as &$bank )
{
// prevent sql injection
$bank = mysql_real_escape_string($bank);
}
// add all values to an 'IN' clause
$banksWhereClause = "bank_name IN ('" . implode("', '", $banksToSearch) . "')";
}
if ( empty($banksWhereClause) )
{
$banksWhereClause = '1';
}
$found = array();
// build the final query
$sql = 'SELECT * FROM bank WHERE ' . $banksWhereClause;
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) )
{
$found[] = $row;
}
var_dump($found);
}
If you need some extra explanations, just ask.
精彩评论