Saroar Saroar - 5 months ago 11
PHP Question

PHP- how to get values from checked checkboxes and corresponding textboxes

I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.

This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.

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

$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);

while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>

<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />

<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>


This is how my form looks --

Suppose the user checks the first three boxes , and enters the values like in this picture - enter image description here

when I click add, I get the values --

Physics

Math

Chemistry

by using the code below:

<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>


but how do I get the values like this-

Physics,40,30

Math,40,30

Chemistry,30,25


I want this output in a variable so that I can store it in my database table.

I have spent several hours behind this in last few days. Please help me with this one.

Answer
  1. you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.

  2. Second, you need to write PHP code, that's concatenating those values.

For example, your HTML code might be:

<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />     

and your PHP code might be:

if (isset($_POST['submit'])) {
    if (!empty($_POST['req_sub'])) {
        foreach ($_POST['req_sub'] as $selected) {
            $total = $_POST['total'][$selected];
            $pass = $_POST['pass'][$selected];
            $var = $selected . ',' . $total . ',' . $pass;
            echo $var . '<br />';
        }
    }
}