根据所选复选框进行过滤

根据所选复选框进行过滤

问题描述:

I have some checkboxes for each movie genre. Each checkbox (movie genre) comes from the db, so there is one checkbox for each movie genre.

 <input type='checkbox' name='movieGenre[]' value='Comedy'>Comedy/>
 <input type='checkbox' name='movieGenre[]' value='Action'>Action/>
 ...

The user can select 1 or more checkboxes and then click in a button "Show" and it should be displayed a table with movies associated with the movie genres checked.

However, to achieve this is necessary to verify which checkboxes are checked and do a query to show only the movies that are associated with the selected checkboxes (movie genres). Do you know what is necessary for this?

To get you started, here is a quick example

//...

if ( ! empty ( $_POST['movieGenre'] ) && is_array ( $_POST['movieGenre'] ) )
{
    // bind param container

    $query = [];

    // bind param types, (s)

    $binds = '';

    // trim and remove possible empty values

    $selected = array_filter ( array_map ( 'trim', $_POST['movieGenre'] ) );

    // go through the $_POST data

    foreach ( $selected AS $genre )
    {
        // valid data should only contain [a-zA-Z]

        if ( ctype_alpha ( $genre ) )
        {
            // valid data, build up the (OR) clause

            $query[] = $genre;

            $binds .= 's';
        }
    }

    if ( ! empty ( $query ) )
    {
        // db connect

        // db statement

        // db prepare

        // db bind

        // db execute

        // db result

        // while ( db fetch )

        // db free result

        // db close
    }
    else
    {
        // error, all $_POST data was invalid
    }
}
else
{
    // error, nothing selected
}

//...