Over a million developers have joined DZone.

PHP Dynamic Checkbox Table Creator (data Retrieved From MySQL DB)

Hi All.
This is a function for Dynamically Create a Checbox Table retrieving information for from a MySQL Database.
As it is quite commented, it's also good for learning how this things work :)
Hope you find it useful.
Feedback is welcome.

function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked="S", $cant_cols_tbl=3){
	by Daniel Neumann
	this script creates dynamically permite a table containing checkboxes 
	getting the data for the checkboxes from a MySQL DB
	$sql_str, SQL select string to retrieve data from DB (see example in last comment line)
	$col_label, DB column that has values for the checkbox label 
	$col_name, DB column that has values for the checkbox name
	$val_checked="S", value when checked (value="" attribute) it uses the same value for all of them. If you whish to use a dynamic value from a DB, you should comment the line (it´s explained next to the code in the middle of the function) and de-comment the other line (check the code,. you'll understand what I mean). Also, you should use this parameter to specify the column name for the values
	$cant_cols_tbl=3, quantity of columns for the table, it defaults to 3
	usage example: dynamic_checkbox_table("SELECT * FROM keywords", "Keyword", "ID_Keywrd");
	//connect DB and run query
	@mysql_select_db($db) or die ("cannot connect to DB");
	$q_resultado = mysql_query($sql_str);
	if (mysql_num_rows($q_resultado)==0) exit("no rows returned");
	$next_row = mysql_fetch_array($q_resultado); //fetch first row
	$output = "\n"; //open table tag
	do {
		$output .= "\n"; //open row tag
		for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl
			$row=$next_row; //assign $row, next row will be checking next one, that avoids starting a new row when it's gonna be empty
			$output .= "\n"; //close TD
		} //close for loop
		$output .= "\n"; //close row
	} while ($next_row); //close do-while (and checks if there's another row)
	$output .= "
"; //open TD tag $output .= (!$row) ? "" : ''.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****) // echo (!$row) ? "" : ''.$row[$col_label]; //create checkbox and data from $row (**** you should de-comment this line if you whish to use dynamic $val_checked****) $next_row = mysql_fetch_array($q_resultado); //retrieve next row $output .= "
\n"; //close table return $output; }

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}