Checkboxes
| From: | Intruder | Date: | Fri, 12 Oct 2001 15:37:28 +0000 |
| Subject: | Checkboxes | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-70933@lists.php.net to get a copy of this message | ||
Hi All,
I have a question concerning checkboxes on the FORM.
As example:
1)
<form name="form1" method="POST" action="<?php echo $PHP_SELF
?>">
<?php
// This code reads some lines from db table and writes checkbox and about field
// content directly after it.
$sql= "SELECT id, about, active .... FROM table WHERE
some_field='$some_value'";
$res= mysql_query($sql);
if (mysql_num_rows($res)>0) {
while ($row=mysql_fetch_array($res)) {
if ($row["active"]==1) {
$box="CHECKED";
} else {
$box="";
};
printf('<input type="checkbox" name="active%s"
%s>',$row["id"],$box);
echo $row["about"];
};
};
?>
<input type="submit" name="sub1" value="UPDATE BUTTON!">
</form>
It produces something like this on the requested page:
|v| Some about 1
| | Some about 2
|v| Some about 3
| | Some about 4
|v| Some about 5
|v| Some about 6
|v| Some about 7
|UPDATE BUTTON!|
The code one can use to handle this:
<?php
if ($sub1) {
reset ($HTTP_POST_VARS);
// Set active field to "0"(FALSE) for ALL the records satisfying WHERE clause
$sql="UPDATE table
SET active=0
WHERE some_field='$some_value'";
mysql_query($sql);
while (list ($name, $val)=each($HTTP_POST_VARS)) {
if (substr($name,0,6)="active") {
$id=substr($name,0,6);
$sql="UPDATE table
SET active=1
WHERE some_field='$some_value' AND
id='$id'";
mysql_query($sql);
};
};
};
?>
2)
<form name="form1" method="POST" action="<?php echo $PHP_SELF
?>">
<?php
// This code produces the same visual HTML output, but it slightly differs
// from the previous one
$sql="SELECT id, about, active .... FROM table WHERE
some_field='$some_value'";
$res=mysql_query($sql);
if (mysql_num_rows($res)>0) {
while ($row=mysql_fetch_array($res)) {
if ($row["active"]==1) {
$box="CHECKED";
} else {
$box="";
};
printf('<input type="hidden" name="new%s"
value="active%s">',$row["id"],$row["id"]);
printf('<input type="checkbox" name="active%s"
%s>',$row["id"],$box);
echo $row["about"];
};
};
?>
<input type="submit" name="sub1" value="UPDATE BUTTON!">
</form>
The code one can use to handle 2nd variant:
<?php
if ($sub1) {
reset ($HTTP_POST_VARS);
while (list ($name, $val)=each($HTTP_POST_VARS)) {
if (substr($name,0,3)="new") {
if ($$val!="") { // Pay attention to this line.!!!!!!!!!!!!!!
$id=substr($name,0,3);
$sql="UPDATE table
SET active=1
WHERE some_field='$some_value' AND
id='$id'";
mysql_query($sql);
};
};
};
};
?>
So, my questions are:
1)
are there any more variants which could be "more correct", faster, easier and
better ??? Just because I don't like them both. First variant is stupid (I used
it when I started with MySQL/PHP) and second produces more HTML...
2)
which variant you'd prefer to use from this two ???
Waiting for reply! ;-)