Reputation: 25
I want insert multiple checkbox values in Mysql using PDO.
HTML Form part checkbox
<form action="insert.php">
<label>
<input name="check[]" id="check[]" type="checkbox" value="<?=$row['id']?>" />
<span class="lbl"></span>
</label>
<button type="submit" name="send" id="send" >
</form>
PHP Part insert
$checkbox = $_POST['check'];
for (i$=0; $i<sizeof($checkbox);$i++)
$insert = $pdo->prepare("INSERT INTO table (check_value) VALUES (?)");
$insert->execute(array(".$checkbox[$i]."));
More when i use ".$checkbox[$i]." give "Notice: Array to string conversion"
Upvotes: 1
Views: 2571
Reputation: 15619
One way to do this is build the SQL dynamicaly.
Just add as many ?
to the SQL as there are checkbox values.
<?php
if (isset($_POST['check'])) {
$sql = 'INSERT INTO TABLE (check_value) VALUES ({foo})';
$foo = '';
foreach($_POST['check'] as $key => $value) $foo .= '?,';
$foo = rtrim($foo, ',');
$sql = str_replace('{foo}', $foo, $sql);
$insert = $pdo->prepare($sql);
$insert->execute($_POST['check']);
}
Upvotes: 1