简体   繁体   中英

An array of POST in one string separated by a comma PHP

I made a form from the checkbox, I want all checked checkboxes to be displayed (ultimately saved to MySQL) as one variable.

Code to display checkboxes in forms (it's working fine):

...
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<div class='form-check'>";
        echo "<label class='form-check-label'>";
        echo "<input class='form-check-input' name='prog[]' type='checkbox' value='".$row['name']."'>";
        echo "<span class='checkbox-icon'></span>";
        echo "<span class='form-check-description'>".$row['name']."</span>";
        echo "</label>";
        echo "</div>";
    }
}
...

and here I 'm display array from a checkbox in input:

...
$N = count($_POST['prog']);
for($i=0; $i < $N; $i++){
    echo "<div class='input-group input-group-sm mb-3'>
          <input name='programnames[]' value='".$_POST['prog'][$i]."' class='form-control' aria-label='Small' aria-describedby='inputGroup-sizing-sm' readonly>
          </div>";
}
...

The problem is that I see the values ​​in separate inputs box. Ultimately, I want to achieve one string (variable). The values ​​to be separated by a comma, like this for example: (TextBox1.Val), (TextBox2.Val) etc

So if I select Tomato and Cucumber I want to have in the variable: Tomato, Cucumber

prog should be an array or null , so you should just be able to implode it:

// Make sure we have an array, even if the data wasn't sent
$progChoices = $_POST['prog'] ?? [];
$joinedChoices = implode(',', $progChoices);

You can then echo your HTML as you are already:

echo "<div class='input-group input-group-sm mb-3'>
      <input name='programnames' value='".$joinedChoices."' class='form-control' aria-label='Small' aria-describedby='inputGroup-sizing-sm' readonly>
      </div>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM