Page 1 of 1

Check Box Layout and Validation

Posted: Thu Sep 28, 2006 5:47 am
by dandare
Hi, I was wodering if anyone can help me with a problem I am having with validating mulitple values from a series of checkboxes.

This is my form at the moment:

Code: Select all

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<?php

echo '<table><tr>';

$query = "SELECT cityID, city FROM tblUrlcity ORDER BY city ASC";
$result = mysql_query ($query);

while($row = mysql_fetch_array ($result, MYSQL_NUM)) {

extract($row);
echo '<td><input type="checkbox" class="formstyle" name="cinterests[]" value="' ,$row[0], '">' ,$row[1], '</td>';
}

echo '</tr>';

echo '<tr><td><input type="submit" value="SELECT" class="button"/></td></tr></table>';

?>
</form>
and the submit code, which at the moment is only submitting a single value, though as many as four can be checked:

Code: Select all

// city interests
if (isset($_POST['cinterests'])) {
$cintr = NULL;
foreach ($_POST['cinterests'] as $key
=> $value) {
$cintr .= "$value, ";
}
$cintr = substr($cintr, 0, -2); //cut off the last comma-space.
$cint = TRUE;
}else{
$cint = NULL;
$message .= '<p>You forgot to enter your city interest(s).</p>';
}
tblUrlcity contains these values:

1 London
2 New York
3 Miami
4 Bristol

Also is there any way to sort the retrieved checkboxes so that after 4 column of data, the next checkbox falls under a new <tr>?

I would appreicate any help given.

Thank you in advance

Posted: Thu Sep 28, 2006 6:08 am
by aaronhall
There's no need for your extract() call in the while loop. Try print_r($_POST['cinterests']) and see what's in the array. To get them into a 4-column table, something like this (not tested):

Code: Select all

<?

echo '<table>';

$query = "SELECT cityID, city FROM tblUrlcity ORDER BY city ASC";
$result = mysql_query ($query);

$counter = 0;

while($row = mysql_fetch_array ($result, MYSQL_NUM)) {
	
	if($counter == 0) { // print the very first <tr>
		echo "<tr>";
		$counter++;
	} elseif($counter == 5) { //done with this row
			echo "</tr>\n<tr>";
			$counter = 1; // reset the counter
	}
	
	echo '<td><input type="checkbox" class="formstyle" name="cinterests[]" value="' ,$row[0], '">' ,$row[1], '</td>';

	$counter++;
} 

// print empty columns to fill up the row
for($i=$counter; $i<=4; $i++) {
	echo "<td></td>";
}

echo "</tr></table>";

?>

Posted: Thu Sep 28, 2006 8:17 am
by dandare
hi Aaronhall

Thanks for the reply, and also the explanation behind the coding.
I will see if this works.

Many thanks again :D