• Home
  • PHP
  • Keep checkboxes checked with MySQL and PHP

Keep checkboxes checked with MySQL and PHP

Most of the time we have a website or a back-end solution, written in PHP, where we use check-boxes as “flags” (to activate a user or a product for example – 1=active, 0=inactive).

Below is the example that I will base on our fictional “products” page in the back-end solution, where we specify if a given product is active or inactive (in order to show or hide it on the front of the site).
First we created a field in our products table in the database. It is a TINYINT field with a length/value of 1. We will call this field “active”.

On our PHP page for a product we usually have a table, which holds a form, which we then submit and the values are updated in the database for that specific productID. So we will add a new row to our HTML, containing a check-box for “active”:

This check-box will become checked if the value in the database equals to 1.

At the very top of the page (before you save your data) you add:

We need this line to process a saved value for “active” after we submit a form. We will use this value (either 1, if checked or 0, if not checked) to update our database table later on, like so:

All done.

Tags: , , ,

Trackback from your site.

Leave a comment