I am trying to get a grasp on how to properly understand how POST works, and decided to make a little php program that generates 100 checkboxes, and at the click of the button on the top of the document, a function is called that loops through all of the checkboxes and states whether or not they are checked. However, it seems like the way I am implementing it does not work.
Here is a more sequential step by step process of what I was thinking as I was writing this script, I would appreciate if someone could tell me the flaw in my thinking.
- Create a button in a form with
method=post
. - Create an array in PHP to store all the checkbox names.
- Create a for loop. In each iteration of the loop, a string is created with the format of
#checkbox
so each checkbox has their own unique identifier. Each one of these strings is stored into an array. PHP then echo's out a form withmethod=post
with a checkbox inside each form. Each checkbox has their own unique name. - After each checkbox is created, you are able to see if each checkbox is checked or not by clicking the button, which calls the
checkFunction()
function. - In the function, there is a
foreach
loop. This loop goes through each element in the array to fetch the checkbox name, usesisset
to see if the checkbox is checked or not, and echo's out if it is.
This seems simple enough to me, but it doesn't seem to work for whatever reason. Could anyone shed some light as to why not?
<!DOCTYPE html>
<html>
<head>
<title>Checked Boxes</title>
</head>
<body>
<form method="post">
<input type="submit" name="submit_checked" class="button" value="Check if checkbox is checked"/>
</form>
<?php
$checkboxNames = array();
for ($x = 1; $x <= 100; $x++) {
$checkboxStr=$x."checkbox";
$checkboxNames[] = $checkboxStr;
echo "<form method=\"post\"><input type=\"checkbox\" name=\"$checkboxStr\" value=\"$checkboxStr\">$checkboxStr</form>";
}
echo("<hr>");
echo("<h2>Status of Checkboxes:</h2>");
function checkFunction(){
foreach ($checkboxNames as $currentName){
if (isset($_POST["$currentName"]))
echo("<p>$currentName is checked!</p>");
else
echo("<p>$currentName is not checked!</p>");
}
}
if(isset($_POST['submit_checked']))
checkFunction();
?>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire