?
Solved

Array checkbox foreach

Posted on 2011-10-30
20
Medium Priority
?
515 Views
Last Modified: 2012-05-12
This small piece of code is killing me today.

I have a loop that is pulling checkbox information out of a database, like the following:
echo "<form action=\"checking.php\">";
echo "<table><tbody>";
echo "<th>Stamp Name</th>";
echo "<th>Approval</th>";

$sql="SELECT * FROM table WHERE transaction='25'";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
$stampid=$row["StampID"];
$stamidp=htmlspecialchars($stampid);
$stampid=mysql_real_escape_string($stampid);
$stamp=$row["Stamp"];
$stamp=htmlspecialchars($stamp);
$stamp=mysql_real_escape_string($stamp);
$approve=$row["Approve"];
$approve=htmlspecialchars($approve);
$approve=mysql_real_escape_string($approve);

echo "<tr><td>";
echo $stamp;
echo "</td><td>";
if ($approve=="1")
{
echo "<center><input type=\"checkbox\"  checked=\"yes\" name=\"app[]\"></center>";
}
elseif ($approve=="0")
{
echo "<center><input type=\"checkbox\" name=\"app[]\"></center>";
}
echo "</td><td>";
}
echo "</tbody></table>";
echo "</form>";

Open in new window


However, within checking.php, I can`t access an empty array using a foreach loop, so what would I use if they uncheck or leave the checkbox empty?
0
Comment
Question by:happysunny
  • 7
  • 6
  • 4
  • +1
19 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 37053974
I don't really understand what is your problem, but if they leave checkbox empty (or if they uncheck checkbox), simply that checkbox value will not be passed and it will not be present in the array...
0
 
LVL 4

Author Comment

by:happysunny
ID: 37054003
Yes, but if it is checked in the database, and they uncheck it on the form, I will need to change it to 0 in the database.
0
 
LVL 4

Expert Comment

by:CKY092
ID: 37054060
I'm not sure if I'm 100% understanding your problem correctly, but the way I'm interpreting it, the following would work:

<?
$app = $_POST['app'];

if($app){
	echo "Update DB with Approved = 1";
}else{
	echo "Update DB with Approved = 0";
}?>

<form action='' method='POST'>
	<input type='checkbox' name='app[]' <? if($app){ echo "checked='checked'"; } ?> /> Approved<br />
	<input type='submit' value='submit' />
</form>

Open in new window


Basically, just check if the array exists... If it does, it's approved, if not, in't not approved.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 4

Expert Comment

by:CKY092
ID: 37054063
*it's
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 37054065
Hmmm, I would like something like this:

if (isset($_POST['app')){
  $sql="UPDATE table SET approve="1" WHERE transaction=25";
}else{
  $sql="UPDATE table SET approve="0" WHERE transaction=25";
}
mysql_query($sql);

Hope this helps.

Cheers
0
 
LVL 4

Author Comment

by:happysunny
ID: 37054075
But there are multiple entries coming out of the database.  Am I over-thinking again?

For instance, when I use the following code and check the box and submit, it goes in checked.  But if I try to uncheck the box and submit, I get the following error: "Warning: Invalid argument supplied for foreach() in...."  That's because it doesn't read it when it's unchecked.  Can you see what I'm doing wrong?

Edit the form:
echo "<form action=\"checking.php\">";
echo "<table><tbody>";
echo "<th>Stamp Name</th>";
echo "<th>Approval</th>";

$sql="SELECT * FROM table WHERE transaction='25'";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
$stampid=$row["StampID"];
$stamidp=htmlspecialchars($stampid);
$stampid=mysql_real_escape_string($stampid);
$stamp=$row["Stamp"];
$stamp=htmlspecialchars($stamp);
$stamp=mysql_real_escape_string($stamp);
$approve=$row["Approve"];
$approve=htmlspecialchars($approve);
$approve=mysql_real_escape_string($approve);

echo "<tr><td>";
echo $stamp;
echo "</td><td>";
if ($approve=="1")
{
echo "<center><input type=\"checkbox\"  checked=\"yes\" name=\"app[$stampid]\"></center>";
}
elseif ($approve=="0")
{
echo "<center><input type=\"checkbox\" name=\"app[$stampid]\"></center>";
}
echo "</td><td>";
}
echo "</tbody></table>";
echo "</form>";

Open in new window


And then for checking.php:
foreach($_POST['app'] as $id => $value) {

if (isset($_POST["app"]))
{
$approval="1";
}
else
{
$approvaldb="0";
}
$sql="SELECT * FROM table WHERE transaction='25'";
$result = mysql_query("UPDATE table SET Approve='$approvaldb' WHERE StampID='$id' limit 1") or die(mysql_error());  
}

Open in new window


0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37054205
Here is a strategy that may be useful for you... Since unchecked checkboxes do not appear in the request at all, you can use a hidden form input element to set a default value for the checkbox.  Simply place an input type="hidden" tag with the same name as the checkbox immediately before the checkbox in the form.

This article might have some other ideas that could be helpful...
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_5450-Common-Sense-Examples-Using-Checkboxes-with-HTML-JavaScript-and-PHP.html
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 37054269
Great trick, Ray! I would never had thought about :-)
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37054524
@marqusG:  Thanks for your note.  I have learned a lot from your many contributions to EE.  

It's never failed me yet.  Empty text inputs are present but empty (NULL strings).  I have no idea why empty checkboxes and radio buttons are left out of the request string, but they are.  And since it has been this way since the days of Berners-Lee it's too late to fix it now!

Warm regards, ~Ray
0
 
LVL 4

Author Comment

by:happysunny
ID: 37054536
Thank you, Ray :)  But now I've really done it LOL  When I use this code, it puts every single entry as being checked in the database!  Yikes!  What am I doing wrong?

The form:
echo "<form action=\"checking.php\">";
echo "<table><tbody>";
echo "<th>Stamp Name</th>";
echo "<th>Approval</th>";

$sql="SELECT * FROM table WHERE transaction='25'";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
$stampid=$row["StampID"];
$stamidp=htmlspecialchars($stampid);
$stampid=mysql_real_escape_string($stampid);
$stamp=$row["Stamp"];
$stamp=htmlspecialchars($stamp);
$stamp=mysql_real_escape_string($stamp);
$approve=$row["Approve"];
$approve=htmlspecialchars($approve);
$approve=mysql_real_escape_string($approve);

echo "<tr><td>";
echo $stamp;
echo "</td><td>";
if ($approve=="1")
{
echo "<input type=\"hidden\"   name=\"app[$stampid]\">";
echo "<center><input type=\"checkbox\"  checked=\"yes\" name=\"app[$stampid]\"></center>";
}
elseif ($approve=="0")
{
echo "<input type=\"hidden\"   name=\"app[$stampid]\">";
echo "<center><input type=\"checkbox\" name=\"app[$stampid]\"></center>";
}
echo "</td><td>";
}
echo "</tbody></table>";
echo "</form>";

Open in new window


Now the code:
foreach($_POST['app'] as $id => $value) {

if (isset($_POST["app"]))
{
$approvaldb="1";
}
else
{
$approvaldb="0";
}
$sql="SELECT * FROM table WHERE transaction='25'";
$result = mysql_query("UPDATE table SET Approve='$approvaldb' WHERE StampID='$id' limit 1") or die(mysql_error());  
}

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37054605
isset() might need to be replaced with empty()
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37054610
Or maybe something else; I am not sure and I recommend the use of var_dump($_REQUEST) to see what is coming into the script. from the external data  The use of isset() would make sense if there were no definition of the field -- It is either set or not set.  But a field can be set and can be empty, too.  Example:

$x = NULL;
if (isset($x)) echo "X is set";
if (empty($x)) echo "X is empty";
0
 
LVL 4

Author Comment

by:happysunny
ID: 37054648
I used var_dump and when it is unchecked, it says:

string(0) ""

but when it is checked it says:

string(0) "on"

That is when I use either isset or empty.
0
 
LVL 4

Author Comment

by:happysunny
ID: 37054695
I'm so stumped LOL  I wonder if there is a way to do this through JavaScript.  Any idea?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37054804
I think we need to see the HTML, the action script, and the inputs, thanks.
0
 
LVL 4

Author Comment

by:happysunny
ID: 37054943
This is it...
<?php
include ("dbinfo.php");
include ("checking.php");
?>
<HTML>
<head>
<title>Add test</title>
</head>
<body>
<?php
$self=$_SERVER['PHP_SELF'];
echo "<form action=\"$self\">";
echo "<table><tbody>";
echo "<th>Stamp Name</th>";
echo "<th>Approval</th>";

$sql="SELECT * FROM stamptesting WHERE transaction='25'";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
$stampid=$row["StampID"];
$stampid=htmlspecialchars($stampid);
$stampid_sq=mysql_real_escape_string($stampid);
$stamp=$row["Stamp"];
$stamp=htmlspecialchars($stamp);
$stamp_sq=mysql_real_escape_string($stamp);
$approve=$row["Approve"];
$approve=htmlspecialchars($approve);
$approve_sq=mysql_real_escape_string($approve);

echo "<tr><td>";
echo $stamp;
echo "</td><td>";
if ($approve_sq=="1")
{
echo "<input type=\"hidden\"   name=\"app[$stampid_sq]\">";
echo "<center><input type=\"checkbox\"  checked=\"yes\" name=\"app[$stampid_sq]\"></center>";
}
elseif ($approve_sq=="0")
{
echo "<input type=\"hidden\"   name=\"app[$stampid_sq]\">";
echo "<center><input type=\"checkbox\" name=\"app[$stampid_sq]\"></center>";
}
echo "</td><td>";
}
echo "</tbody></table>";
echo "<table><tbody>";
echo "<tr><td>";
echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">";
echo "</td></tr>";
echo "</tbody></table>";
echo "</form>";
?>
</body>
</html>

Open in new window


and then checking.php:
<?php
include ("dbinfo.php");

if(isset($_POST['submit']))
{

var_dump($_REQUEST);

foreach($_POST['app'] as $id => $value) {

if (!empty($_POST["app"]))
{
$approvaldb="1";
}
elseif (empty($_POST["app"]))
{
$approvaldb="0";
}
$result = mysql_query("UPDATE stamptesting SET Approve='$approvaldb' WHERE StampID='$id' limit 1") 

or die(mysql_error());  
}
}
?>

Open in new window


This is where you can play around with it.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 37055493
@Ray I really can't believe you lerned something from me: I'm only an amateur whereas in each line of your snippets is evident you are a very experienced professional programmer and a very good teacher... btw, have you never thought to write a book including your articles and your knowledge about best techniques in writing elegant a robust code? IMHO, You should think about. Anyway, thanks for your pleasentry.

@happysunny. I tested this little snippets and it does exactly what it is expected to do - and what you are trying to do:
   
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (isset($_POST['submit'])){
    echo "<pre>";
    var_dump($_POST['app']);
    foreach ($_POST['app'] as $k=>$v){
        if (empty($v)){
            echo "$k isunchecked<br />";
        }else{
            echo "$k is checked<br />";
        }
    }
}else{
echo "<form id='' action='" . $_SERVER['PHP_SELF'] . "' method='post'>";
echo "<table>";
echo "<tr>";
echo "<td>";
echo "<input type='hidden' id='' name='app[0]' value='' />";
echo "<input type='checkbox' id='' name='app[0]' value='app0' />";
echo "</td>";
echo "<td>";
echo "<input type='hidden' id='' name='app[1]' value='' />";
echo "<input type='checkbox' id='' name='app[1]' value='app1' />";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<input type='hidden' id='' name='app[2]' value='' />";
echo "<input type='checkbox' id='' name='app[2]' value='app2' />";
echo "</td>";
echo "<td>";
echo "<input type='hidden' id='' name='app[3]' value='' />";
echo "<input type='checkbox' id='' name='app[3]' value='app3' />";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<input type='submit' id='submit' name='submit' value='Submit' />";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</form>";


}
?>

Open in new window

As you see, I use Ray's suggestion and I get always for values:

array
  0 => string 'app0' (length=4)
  1 => string '' (length=0)
  2 => string '' (length=0)
  3 => string '' (length=0)

So you should be able to update database seriously. I don't understand where is the problem now.

And now I leave you in the Ray's hands, better than mines

Cheers
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 37056416
Looking at this post, ID:37054648...  You can assign a name and a value to the checkbox.  That way you will get something more useful than "on" when it is checked.

Looking at this post, ID:37054943... Please see the code snippet.  I have just copied the code there and lined up the control structures.  This seemingly simple act of lining up the code is part of a larger process called "coding standards."  If you apply it consistently, a coding standard will really help your thought processes and accuracy.  I think the issue may have been caused by looking at $_POST["app"] instead of looking at the parts of that array.  I cannot test this because I do not have your data base, but hopefully the principles will be clear as you read over this snippet.

HTH, ~Ray

PS: Read that article.  You might also enjoy this little book, and the PHP web site has a tutorial on handling forms.
http://www.sitepoint.com/books/phpmysql4/
http://php.net/manual/en/tutorial.forms.php
<?php
// ALWAYS SHOW ALL THE ERRORS DURING THE DEVELOPMENT CYCLE
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

// CONNECT AND SELECT A DATA ASE
include ("dbinfo.php");

// IF THE POST HAS BEEN SUBMITTED
if(!empty($_POST))
{
    // ACTIVATE THIS TO SHOW THE POST DATA
    // var_dump($_POST);

    // ITERATE OVER THE "app" ARRAY USING $id AND $value TO GET AT THE VARIABLES
    foreach($_POST['app'] as $id => $value) 
    {
        // ASSUME THE VALUE IS NOT SET
        $approvaldb="0";
        
        // TEST TO SEE IF THE VALUE IS SET
        if (!empty($value))
        {
            $approvaldb="1";
        }
        
        // UPDATE THE DATA BASE 
        $result = mysql_query("UPDATE stamptesting SET Approve='$approvaldb' WHERE StampID='$id' limit 1") or die(mysql_error());  
    }
}
else
{
    echo "NO POST DATA!";
}

Open in new window

0
 
LVL 4

Author Comment

by:happysunny
ID: 37057513
@marqusG & @CKY092 Thank you for you trying to help!

@Ray_Paseur I couldn't agree more with marqusG on you writing your own book.  You're brilliant!  Thank you so much :)
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to count occurrences of each item in an array.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
Suggested Courses
Course of the Month15 days, 11 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question