Jump to content

Dynamic checkboxes question!(again I know)


pthurmond

Recommended Posts

Ok I am having trouble getting a bunch of dynamically generated checkboxes to work right. Here is my new idea and I want to see if more experienced programmers would think this should work. If not does anyone have any better suggestions.

Here is my code to generate the checkboxes:
[code]
$query = "SELECT Activity_ID, Name, Picture FROM Activities";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

if($result)
{
$i = 0;
$loop = 0;

while($row = mysql_fetch_array($result, MYSQL_NUM))
{
if($loop == 0)
{
echo '<tr>';
}

echo '<td width="25"><input name="Activity' . $i . '" type="checkbox" value="' . $row[0] . '"><br>' . $row[1] . '</td>';
echo '<td><img src="' . $row[2] . '" border="1" valign="middle" align="center"></td>';

$i++;

if($loop == 2)
{
echo '</tr>';
$loop = 0;
}
else
{
$loop++;
}
}


if($loop != 0)
{
if($loop == 1)
{
echo '<td>&nbsp;</td><td>&nbsp;</td>';
}
else if($loop == 2)
{
echo '<td>&nbsp;</td>';
}

echo '</tr>';
}

echo '<input name="actcount" type="hidden" value="' . $i . '" >';
}
[/code]


And here is my code to process it:
[code]
$actcount = $_POST['actcount'];
$actarray[0] = 0; //An array of activity ids is being built.

for($k=0; $k < $actcount; $k++)
{
$act = 'Activity' . $k;

if(isset($_POST[$act]))
{
$actarray[$k] = $_POST[$act];
}
}
[/code]

The idea of processing it like this is to have an array of the id numbers that I can then put into the database. I have to check to make sure at least one activity was checked before putting anything into the database.


Thanks,
Patrick
Link to comment
https://forums.phpfreaks.com/topic/28064-dynamic-checkboxes-questionagain-i-know/
Share on other sites

Think this should work! A better way though would be like this:-

[code]$query = "SELECT Activity_ID, Name, Picture FROM Activities";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

if($result)
{
$i = 0;
$loop = 0;

while($row = mysql_fetch_array($result, MYSQL_NUM))
{
if($loop == 0)
{
echo '<tr>';
}

echo '<td width="25"><input name="Activity[]" type="checkbox" value="' . $row[0] . '"><br>' . $row[1] . '</td>';
echo '<td><img src="' . $row[2] . '" border="1" valign="middle" align="center"></td>';

$i++;

if($loop == 2)
{
echo '</tr>';
$loop = 0;
}
else
{
$loop++;
}
}


if($loop != 0)
{
if($loop == 1)
{
echo '<td>&nbsp;</td><td>&nbsp;</td>';
}
else if($loop == 2)
{
echo '<td>&nbsp;</td>';
}

echo '</tr>';
}
}[/code]

And the second code could be like this:-

[code]$actarray = $_POST[$Activity];[/code]

Basically, [b]$_POST[$Activity][/b] will be an array containing the values of all the checkboxes that have been checked.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.