Array checkbox foreach

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?
LVL 4
happysunnyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
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
happysunnyAuthor Commented:
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
CKY092Commented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

CKY092Commented:
*it's
0
Marco GasiFreelancerCommented:
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
happysunnyAuthor Commented:
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
Ray PaseurCommented:
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
Marco GasiFreelancerCommented:
Great trick, Ray! I would never had thought about :-)
0
Ray PaseurCommented:
@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
happysunnyAuthor Commented:
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
Ray PaseurCommented:
isset() might need to be replaced with empty()
0
Ray PaseurCommented:
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
happysunnyAuthor Commented:
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
happysunnyAuthor Commented:
I'm so stumped LOL  I wonder if there is a way to do this through JavaScript.  Any idea?
0
Ray PaseurCommented:
I think we need to see the HTML, the action script, and the inputs, thanks.
0
happysunnyAuthor Commented:
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
Marco GasiFreelancerCommented:
@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
Ray PaseurCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
happysunnyAuthor Commented:
@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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.