In php a checkbox is present (and contains the value) in the $_REQUEST
(or $_GET
or $_POST
) if it is checked. Otherwise it is not present. So to get whether your checkbox is checked or not you can use the following:
$is_checked = isset($_POST["checkbox_name"]);
To print the checkbox value use the checked
html attribute. If it is given, the checkbox will be ticked.
print(
"<input ".
"type='checkbox' ".
"name='checkbox_name' ".
(isset($_POST["checkbox_name"]) ? "checked='checked' " : "").
" />"
);
To work with a dynamic number of elements I use arrays in the $_POST
(or $_REQUEST
). You can do this by adding [
and ]
to the end of the name
attributes of your inputs (e.g. like in https://www.php.net/manual/reserved.variables.post.php#87650). An alternative is to use suffixes or prefixes (e.g. checkbox_name_1
) but in my opinion this is just a little bit more work to do.
To add new inputs your javascript may look like the following snippet. The name is always the same, just a [<index>]
is appended to tell php to handle this as an array. The <index>
is the numeric index to use. This is important, otherwise you cannot use isset($_POST[...][$index])
because dynamic indices will "fill up" your checkbox values.
$("#add").on("click", function(){
let i = $("#table tr").length;
$("#table").append(
"<tr>" +
"<td>Name <input type='text' name='name[" + i + "]' /></td>" +
"<td>Is solo parent <input type='checkbox' name='is_solo_parent[" + i + "]' /></td>" +
"<td>Is employeed <input type='checkbox' name='is_employeed[" + i + "]' /></td>" +
"</tr>"
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<table id="table">
</table>
In php then you can iterate over the requested variables and check if they exist:
foreach($_POST["name"] as $i => $name){
// the "name" exists, if no name is given, no entry in the database is wanted
$is_solo_parent = isset($_POST["is_solo_parent"][$i]); // true or false
$employeed = isset($_POST["employeed"][$i]); // true or false
$database->insert($name, $is_solo_parent, $employeed);
}
$database->insert()
is of course a function that fills the data into your database. Make sure to escape user input to prevent script injection and best use prepared statements to prevent sql injection.