Introduction
Over in the php help forum, the question of how to deal with checkboxes arises pretty often. Usually, people want to be able to select which rows of a database to update/delete/throw out the window.
The concept is actually pretty simple. It involves naming your checkbox as an array and the use of the IN mysql clause. This tutorial aims to give a simple example in the hope that, next time someone asks, I can point them to a tutorial rather than explaining all over again.
Right, on with the show.
The Database
Seeing as we're going to be updating a database, we'll be needing a table and some data. Here's a table I made earlier:
- CREATE TABLE `tutorial_users` (
-
- `id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
-
- `username` VARCHAR( 50 ) NOT NULL ,
-
- `admin` TINYINT( 1 ) NOT NULL DEFAULT '0',
-
- PRIMARY KEY ( `id` )
-
- ) ENGINE = MYISAM
And some data to work with. No prizes for guessing what I was just watching on TV:
- INSERT INTO `tutorial_users` (
-
- `id` ,
-
- `username` ,
-
- `admin`
-
- )
-
- VALUES (
-
- NULL , 'Stewie', '0'
-
- ), (
-
- NULL , 'Peter', '0'
-
- ), (
-
- NULL , 'Brian', '0'
-
- ), (
-
- NULL , 'Meg', '0'
-
- ), (
-
- NULL , 'Lois', '0'
-
- ), (
-
- NULL , 'Chris', '0'
-
- ), (
-
- NULL , 'Greased Up Deaf Guy', '0'
-
- ), (
-
- NULL , 'Quagmire', '0'
-
- );
It's a simple setup. A user's table with a field called admin, which is the field we'll be updating.
If you're the kind of guy (or gal; we're all for equal opportunities here) who likes a quick fix – the full code is on the next page. Otherwise, we'll be breaking it down on pages 4 and 5.
The Code
- include("connect.php");
- $updated = FALSE;
- if(count($_POST) > 0){
- $admin = $_POST['admin'];
- array_map('intval',$admin);
- $admin = implode(',',$admin);
- mysql_query("UPDATE tutorial_users SET admin=0") or trigger_error(mysql_error(),E_USER_ERROR);
- mysql_query("UPDATE tutorial_users SET admin=1 WHERE id IN ($admin)") or trigger_error(mysql_error(),E_USER_ERROR);
- $updated=TRUE;
- }
- ?>
phpfreaks checkbox tutorial - if($updated===TRUE){
- echo 'Privileges Updated!';
- }
- ?>
Username Admin Privileges - $sql = "SELECT id,username,admin FROM tutorial_users ORDER by id ASC";
- $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
- while(list($id,$username,$admin)=mysql_fetch_row($result)){
- $checked = ($admin==1) ? 'checked="checked"' : '';
- echo '
'."\n";'.$username.' - }
- ?>
Interlude
Thanks for sticking around. Before we take a closer look at that code, I just want to mention a little about checkboxes and how they work.
You're probably aware that with a lot of other form elements, such as text fields, if you leave them blank they'll still appear in the $_POST/$_GET array – just with a blank value.
On the other hand, checkboxes behave a bit more like buttons. If you don't check them, they wont appear in the array. Assuming you do tick them, they'll take the value you give them or 'on' by default. Bear that in mind, it'll be important later.
Breaking it down
I'm going to start the breakdown a little way through the code from the opening form tag, seeing as you'll have to fill in that form before you can process it.
- if($updated===TRUE){
- echo 'Privileges Updated!';
- }
We have a standard form with a post method, and an action of the same page. We're also going to display a message if the database was updated – because we're nice like that.
Username Admin Privileges We're going to setup a table with the username and privilege listed in it. If you don't like tables, tough luck.
- $sql = "SELECT id,username,admin FROM tutorial_users ORDER by id ASC";
- $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
We select the fields we need from the database (not forgetting the id, as we'll use this to identify each row) and execute the query with a little error checking.
- while(list($id,$username,$admin)=mysql_fetch_row($result)){
If you're not familiar with the list() construct, it allows us to assign lots of variables from a numerically indexed array in one go. I get bored of using $row all the time, so it makes a change. It's important to use mysql_fetch_row() so that you get a numerically indexed array (as opposed to an associative one) and that you create the variables with the same order you selected them in your query. See the manual page for a bit more.
- $checked = ($admin==1) ? 'checked="checked"' : '';
- echo '
'."\n";'.$username.'
Inside that loop, we first work out if the checkbox should be ticked to start with. That is, if the user currently has admin privileges. Use of the ternary operator keeps this short and sweet. We then echo out a row for each user.
Notice that we name the checkbox admin[]. This means that $_POST['admin'] is going to be an array. An array of all the ticked boxes in fact. Also notice that we set the value to the id of the user.