Filtering data with php

Filter Data with Checkboxes in PHP & MySQL

If you need to filter data with checkboxes in PHP & MySQL for your web application. Then This tutorial will be very helpful for you.

In this tutorial, the checkbox filter data source code is shared with some simple steps that will be very easy to implement into the project.

Some categories will be displayed from the database with checkboxes. When you check a checkbox category then the data will display in tabular form based on that checked checkboxes. If you check multiple checkboxes, then also, data will be filtered for all checked checkboxes.

How to Filter Data with Checkbox using PHP, MySQL

Now, Let’s start the coding to filter data by category with the following simple steps –

Learn Also –

1. Create a Directory Structure

First of all, You should create the following directory structure to filter data by category.

source-code/ |__database.php |__index.php |__filter-data.php |__display-data.php |__get-category.php |

2. Create MySQL Table

Now, Create a MySQL database

CREATE DATABASE codingstatus;

Create a table with the name of the products

CREATE TABLE `products` ( `id` int(10) NOT NULL AUTO_INCREMENT, `productName` varchar(255) DEFAULT NOT NULL, `price` int(20) DEFAULT NOT NULL );

4. Insert Data into MySQL Table

Now, You should insert some records into the MySQL Table. This data will be used to display for the checkboxes and display in the HTML table.

INSERT INTO products(id, productName, category) VALUES (1', 'product-1','category1'), (2', 'product-2','category2'), (3', 'product-3', 'category2'), (4', 'product-4', 'category1'), (5', 'product-5', 'category3'), (6', 'product-6', 'category3'), (7', 'product-7', 'category1'), (8', 'product-8', 'category1'), (9', 'product-9', 'category4'), ('10', 'product-10', 'category3');

3. Setup MySQL Database Connection

Now, You have to connect your PHP to the MySQL database with the following PHP script –

Читайте также:  Иконки рядом с ссылками на документы

In this script, we have declared the table name in the constant variable to use it globally on any page.

define('productTable', 'products');

Get Category From the Database

To display categories dynamically for the checkboxes from the database, You need to write the code according to the following points

  • Create a user-defined function getCategory() and write code within it according to the next all steps
  • make $conn global to use it anywhere in the file
  • create a variable $data with an empty array.
  • Write SQLi Query to fetch unique categories from the database
  • If the category rows are greater than zero then fetch the category with the $result->fetch_all(MYSQLI_ASSOC) and store it in the variable $data
  • At last return the $data to get categories based on filtered category

File Name – get-category.php

query($query); if($result->num_rows > 0) < $data = $result->fetch_all(MYSQLI_ASSOC);; > return $data; >

5. Create a Form to Filter Data

Now, You need to create the price filtering UI by using the following points –

  • Create a basic HTML structure/code
  • Include the database.php, filter-data.php & get-category.php files that will be explained in the next steps.
  • Make a form with the post method.
  • Call the function getCategory and store into the $getCategories
  • print the value of category for the checkbox by applying foreac loop on the $getCategories
  • Create a submit button with the name of filter
  • Include the file display-data.php just after the form.

6. Write Filtering data with a checkbox Script in PHP

To write filtering data with a checkbox, You need to follow the following steps –

  • Start writing code, If the form is submitted then call the function filterDataByCategory() and store in the $filterDataByCategory.
  • Create a user-defined function filterDataByCategory() and write the code according to the next steps.
  • Get the checkbox value using $_POST[‘category’] and store it in the $filterByCategory.
  • $filterByCategory stores an array of values. So, convert it into the string using implode()
  • Declare $conn with the keyword global to use it globally.
  • If $filterByCategory is not empty then write code according to the next points
  • Write MySQLi query to select productName & category
  • If te filtered rows are greater than zero then fetch it with the $result->fetch_all(MYSQLI_ASSOC) and store in the $data.
  • After that, return the value of $data to display records in the datable.
 function filterDataByCategory() < $filterByCategory = $_POST['category']; $categories = "'".implode("', '", $filterByCategory)."'"; global $conn; $data =[]; if(!empty($filterByCategory))< $query = "SELECT productName, category FROM ".productTable; $query .= " WHERE category IN ($categories)"; $result = $conn->query($query); if($result->num_rows > 0) < $data = $result->fetch_all(MYSQLI_ASSOC);; > > return $data; >

7. Display Filtered Data in Table

To display the filtered data in the HTML table, configure the following points –

  • If the $filterDataByCategory has values then write code within it from the next all points.
  • Create the first row of the table with three columns S.N, Product, & category
  • Then create other rows dynamically based on the filtered data with checkbox
  • print the value of columns ‘productName’ and ‘category’ respectively using foreach on the filterDataByCategory.
Читайте также:  Сохранить данные в файл java

File Name – display-data.php

8. Test yourself to filter data by Category

After implementing all the given steps, Now you can test the PHP filtering data by checkbox to open in the web browser.

You will get a select input field with some categories options

  • When you select a category option and submit the form then the records will display in an HTML table related to the filtered category.

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I’m a Software Engineer. I have been working in the Web Technology field for 4 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Источник

PHP Filters

Validating data = Determine if the data is in proper form.

Sanitizing data = Remove any illegal character from the data.

The PHP Filter Extension

PHP filters are used to validate and sanitize external input.

The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.

The filter_list() function can be used to list what the PHP filter extension offers:

Example

Why Use Filters?

Many web applications receive external input. External input/data can be:

  • User input from a form
  • Cookies
  • Web services data
  • Server variables
  • Database query results

You should always validate external data!
Invalid submitted data can lead to security problems and break your webpage!
By using PHP filters you can be sure your application gets the correct input!

PHP filter_var() Function

The filter_var() function both validate and sanitize data.

Читайте также:  Добавление записи в таблицу

The filter_var() function filters a single variable with a specified filter. It takes two pieces of data:

Sanitize a String

The following example uses the filter_var() function to remove all HTML tags from a string:

Example

$str = «

Hello World!

«;
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>

Validate an Integer

The following example uses the filter_var() function to check if the variable $int is an integer. If $int is an integer, the output of the code below will be: «Integer is valid». If $int is not an integer, the output will be: «Integer is not valid»:

Example

if (!filter_var($int, FILTER_VALIDATE_INT) === false) echo(«Integer is valid»);
> else echo(«Integer is not valid»);
>
?>

Tip: filter_var() and Problem With 0

In the example above, if $int was set to 0, the function above will return «Integer is not valid». To solve this problem, use the code below:

Example

if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) === false) echo(«Integer is valid»);
> else echo(«Integer is not valid»);
>
?>

Validate an IP Address

The following example uses the filter_var() function to check if the variable $ip is a valid IP address:

Example

if (!filter_var($ip, FILTER_VALIDATE_IP) === false) echo(«$ip is a valid IP address»);
> else echo(«$ip is not a valid IP address»);
>
?>

Sanitize and Validate an Email Address

The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address:

Example

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) echo(«$email is a valid email address»);
> else echo(«$email is not a valid email address»);
>
?>

Sanitize and Validate a URL

The following example uses the filter_var() function to first remove all illegal characters from a URL, then check if $url is a valid URL:

Example

// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) echo(«$url is a valid URL»);
> else echo(«$url is not a valid URL»);
>
?>

Complete PHP Filter Reference

For a complete reference of all filter functions, go to our complete PHP Filter Reference. Check each filter to see what options and flags are available.

The reference contains a brief description, and examples of use, for each function!

Источник

Оцените статью