Hi there,
This is relatively straight forward to do.
You would do it in three steps:- Using PHP retrieve the number of rows in your database table and store it as a variable
- At the bottom of your document, open a <script> tag and assign the PHP variable to a JavaScript variable, (simply by echoing the PHP variable).
- As you rightly say, use a for loop to output the check boxes.
Here's some code to do all of this:
Code:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$totalRows = $row[0];
echo "Total rows: " . $totalRows;
mysql_close($con);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create checkboxes</title>
</head>
<body>
<p>Here are the check boxes:</p>
<div id="checkboxContainer"></div>
<script>
var numCheckbxes = <?php echo($totalRows) ?>;
var frag = document.createDocumentFragment();
for (i=0; i< numCheckbxes; i++){
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.name = 'myCheckbox[]';
cb.value = 'checkbox-' + i;
frag.appendChild(cb);
}
document.getElementById("checkboxContainer").appendChild(frag);
</script>
</body>
</html>
Bookmarks