platanas20 platanas20 - 2 years ago 62
MySQL Question

Implode function doesn't store data in database table

I am trying to store a string (like 1, 2, 3, ...) in my database table but the stored data is only 1 (I see just 1 in the table column instead of 1, 2, 3, ...).I want to post checkbox_id from a php form and to store these numbers on a table column (the number is depending on which checkboxes are checked and how many of them are checked also).

Here is the code:

<form action="insert.php" method="post"><div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'"> </div></div>

Submit Button (outside the php echo) :

<button type="submit" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>

insert.php :


foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(" ", $sliced);

echo $gift_id;

$stmt_insert = $conn->prepare("INSERT INTO transactions (gift_id) VALUES (:gift_id)"));

$stmt_insert->bindParam(':gift_id', $gift_id);

Answer Source

As you post the checked box values as array, so you have some blank fields. you need to filter them, so use the array_filter.

$filter_arr = array_filter($_POST['opt2']);
$gift_id = implode(",", $filter_arr);

and store the $gift_id into the database, this is the string of checked ids.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download