C
C
cloneforce2020-04-26 14:12:45
PHP
cloneforce, 2020-04-26 14:12:45

How to get data from checkbox?

There is a list of goods. Each product has a checkbox. At the end of the page there is a button like "submit" which sends a POST request to the PHP script.
I can't figure out how to process these checkboxes.
I need to query the database if the product checkbox is enabled.

The checkbox itself looks like this:
<input type="checkbox" name="add-[id]" value="on">

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DanKud, 2020-04-26
@cloneforce

You need to pass an array of checkboxes instead of "add"giving each checkbox a separate name. And from this array you will get the values ​​of the checked checkboxes.
For example:

<input type="checkbox" name="add[]" value="101"> <!-- id товара в value -->
<input type="checkbox" name="add[]" value="102">
<input type="checkbox" name="add[]" value="103">

print_r($_POST['add']); // в $_POST['add'] у вас массив всех отмеченных id

or as suggested in the answer above - send an array with keys and take the values ​​of the keys:
<input type="checkbox" name="add[101]" value="on"> <!-- id товара в ключе массива -->
<input type="checkbox" name="add[102]" value="on">
<input type="checkbox" name="add[103]" value="on">

$ids = array_keys($_POST['add']); // в $ids у вас массив всех отмеченных id
print_r($ids);

V
Vladislav Boychenko, 2020-04-26
@vladislav_boychenko

I created a hidden hidden input, in the value of which I passed the value "Yes / No". This was not for adding to the database, but it was suitable for tracking the checkbox.

F
FanatPHP, 2020-04-26
@FanatPHP

remove the meaningless dash from the field name and write
$ids = array_keys($_POST['add']);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question