0

I have a database with a table a bank, there are 3 fields in that table 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.
If I click the checkbox that appears bank3 I want only records that have a bank3 data only.

How to make it?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what if the script is made with javascript, because if you use PHP you must use the submit button. whereas in javascript do not need to click the submit button, when we click the checkbox data will appear automatically
just catch all on-leaves for the form, set the buttons value manually, and repost the result. do you need an ajax tutorial? Your code will just get some things added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.