checkbox forms[array]

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

checkbox forms[array]

Post by tim »

Well this is simple, I know. but it seems like I answered a few peoples question so I guess it could be a useful code snipplet seeing there are some out there who dont know.

Description: this will grab/display data inside a SQL table and insert it into a form, with checkboxes for each row of data in the table, WHICH will turn the form into a array (for every checked item) and pass to another page for (in this example) processing and deleting (in thsi example, the table will have a id column which of course is auto_incremented). sorry for the big run-on sentence. Hope you find it handy.

First off, displaying the data and the form itself. This is located on index.php

Code: Select all

<?php
// index.php
$sql = "SELECT * FROM table_name ORDER BY id";  //get the data from the table
$result = mysql_query($sql);
//display all the data in the table placing a check box beside each row of data
while ($row = mysql_fetch_array($result)) { 
$id = $row["id"]; // this is our/your auto_increment column

//The form:
echo "<form action=delete.php?$delete method=POST><input type=checkbox name=delete[] value=$id>"; //few things I will explain, notice the delete.php?$delete, this is sending the variable $delete to delete.php (i will get to that later)
//notice the name=delete[], the [] creates the array needed to pass multiple variables, and this will be the $delete var sent via the form action ?$delete.  Also -  the value is set as id.  This will enable us to delete specifics rows as its called/displayed via the while loop.
} // end while loop

//Note that you can display the data inside a table and just make it so the checkbox is to the left, right, above, below, whatever you fancy

//Onto delete.php

<?
if(isset($delete)) { // was the delete variable sent from index.php? is it present
foreach($delete as $id) {  //self explanatory
$del = "DELETE FROM table_name WHERE id=$id"; //now you can see why we set the column name id as a var and set the value of the input form as id.
mysql_query($del);
echo "msg(s) deleted";
 }
}
?>
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Mixing up html in the model isn't such a good idea. For example, you could build an array of vars to describe checkbox field options, then apply html formatting later. The array could be:

Code: Select all

$options[$i]['submitted'] = // the value in text field name="" attribute
$options[$i]['displayed'] = // the value displayed to user (optional - use $submitted if don't need a special display value)
$options[$i]['selected']  = // true/false
An array in this format could be used for checkboxes or <select> options.

Ideally you don't want to be tied to mysql queries. It's best if you can iterate over any type of collection. The class OptionsArrayBuilder, below, is designed to set a new $options element on each loop:

Code: Select all

$preselect  = array('foo', 'bar'); // foo & bar will be preselected
$ob         =& new OptionsArrayBuilder($preselect);

// $it - an iterator 

while($it->isValid())
{
    $ob->setElement($it->getCurrent());
}

$options = $ob->getOptionsArray();
Once you've got an array, it can be passed around for further processing, if required.

To print, loop through the array and wrap it up in <select> tags or whatever.

This is the class used to build the array:

Code: Select all

class OptionsArrayBuilder($preselect = null)
{
    var $i = 0;
    
    // public
    var $options_array;

    /*
        param (array) $preselect - preselected item/s (optional)
    */
    function OptionsArrayBuilder($preselect = null)
    {
        $this->options_array = array();
        $this->preselect = $preselect;
    }

    /*
        param (string) $submitted
        param (string) $displayed - optional
    */
    function setElement($submitted, $displayed = '')
    {
        $this->options_array[$this->i]['submitted'] = $submitted;
        $this->options_array[$this->i]['displayed'] = $displayed;        
        $this->options_array[$this->i]['selected']  = $this->_isPreselected($submitted);          
        $this->i++;
    }

    /*
        return (array)
    */
    function &getOptionsArray()
    {
        return $this->options_array;
    }

    //////////////////////////////////////////
    //              PRIVATE                 //
    //////////////////////////////////////////

    /*
        param (string) $submitted
        return (bool)
    */
    function _isPreselected($submitted) 
    {
        if(is_null($this->preselect))
        {
            return false;
        }
        foreach($this->preselect as $value)
        {
            if($submitted == $value)
            {
                return true;
            }
        }
        return false;
    }
}
///////////////
// END CLASS //
///////////////
Last edited by McGruff on Tue Aug 09, 2005 7:18 am, edited 1 time in total.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

I agree gruff, but do you think a beginner can follow such code you provided? I was being generic.. My main goal was to get the "example" across in a manner a novice could follow and improve on.

sorry for the confusion on my end.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

A fair point perhaps.

I see the code snippets board as a library of php code. Some library items can be focussed on one thing, others are better as "open" as possible.

Library code doesn't have to be tutorial code - just has to be good at what it does and so worth including in a library.

This board is still kind of experimental really so your guess is as good as mine.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

indeed.

If I could have posted it in the tutorial section, I most surely would have. As it was my intention to pass it off as one.

:P
User avatar
g3ckO
Forum Contributor
Posts: 117
Joined: Mon Jul 12, 2004 2:57 am
Location: Malaysia
Contact:

Post by g3ckO »

can anyone explain a little bit about this..

I just don't know how to complete this:

Code: Select all

<?php
session_start(); 
include("database.php");


   $user=addslashes($_SESSION[username]);
 
   $query="SELECT * FROM `leave` a INNER JOIN `employee` b ON b.`StaffNo` = a.`Super` WHERE b.`username` = '$user'AND a.`Status` = 'Pending Review'";
 
   $result=mysql_query($query) or die(mysql_error());
   while ($row = mysql_fetch_array($result))

	{
	$refid=$row["RefID"];

	echo"<form action=leave_app_2.php
?>
I'am trying to get output something like this:

checkbox refId name dateapply status
[] xxx xxx xxx xxx
[] xxx xxx xxx xxx

and finally with the submit button that will submit the value of checked checkbox to insert the row into database.

The main issue is how can I include the checkbox in every row of data that will be echo and how to get the value of checked checkbox.
User avatar
g3ckO
Forum Contributor
Posts: 117
Joined: Mon Jul 12, 2004 2:57 am
Location: Malaysia
Contact:

Post by g3ckO »

:arrow: PHP code section.
Last edited by g3ckO on Tue Aug 17, 2004 4:19 am, edited 1 time in total.
fccolon
Forum Newbie
Posts: 10
Joined: Mon Jul 19, 2004 6:13 am
Location: UK

Post by fccolon »

Hi G3cko,

Sorry I cant help you.....I'm a noob, which was why I was browsing in the Code Snippets section.
To get an answer to you question you'd probably be better off posting in PHP-Code section.
Post Reply