This is the form in which I am using to try and create multiple rows to insert into a database.
<input name="input[]" type="checkbox" value="0" id="input_0" /> Directional<br /> <br/>
<input name="input[]" type="checkbox" value="1" id="input_1" /> Technical <br />
<br />
<input name="input[]" type="checkbox" value="2" id="input_2" /> Reference <br />
<br />
<input name="input[]" type="checkbox" value="3" id="input_3" /> Research <br />
<br />
<input name="input[]" type="checkbox" value="4" id="input_4" /> Phone <br /></h3>
<input type="submit" name="button" id="button" value="Submit Tally" style="height: 25px; width: 100px">
</Form>
Current issue of inserting multiple rows into mysql database from a checkbox form using implode. Would a loop work to fix this issue? I can see the array (#,#,#,#) when check boxes are selected
$type = $_POST['input'];
// $sid = $_SERVER['REMOTE_ADDR'];
$user = $_POST['user'];
if(count($type) > 0)
{
$type_string = implode(',', $type);
}
$sql = "INSERT INTO tally (tid, sid, uid, date, time, catid)
VALUE (NULL, 1, '$user', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '$type_string')";
mysql_query($sql) or die(mysql_error());
echo "Success";
print_r($type_string);
A loop would certainly work, after you created some array from that $type variable you receive as input, and feed this into your query one at the time.
But I hope you're not going to use this code in some website just like this. As maiotano84 already commented, the way you create your query is a little dangerous. It is very easy to do some unwanted things with your data. At least you should put your variables through a function like
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Here is some more info on this function frm the php.net site.
compute the value of $type
as below:
$i=0;
foreach ($_POST as $v) {
if(isset($v['input'.$i])) {
$type = $v;
$i++;
}
}
<Form action="" method="POST">
<input name="input[]" type="checkbox" value="0" id="input_0" /> Directional<br /> <br/>
<input name="input[]" type="checkbox" value="1" id="input_1" /> Technical <br />
<br />
<input name="input[]" type="checkbox" value="2" id="input_2" /> Reference <br />
<br />
<input name="input[]" type="checkbox" value="3" id="input_3" /> Research <br />
<br />
<input name="input[]" type="checkbox" value="4" id="input_4" /> Phone <br /></h3>
<input type="submit" name="button" id="button" value="Submit Tally" style="height: 25px; width: 100px">
</Form>
<?php
$type = $_POST['input'];
// $sid = $_SERVER['REMOTE_ADDR'];
$user = $_POST['user'];
for($i=0;$i<count($type);$i++){
$sql = "INSERT INTO tally (tid, sid, uid, date, time, catid)
VALUE (NULL, 1, '$user', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ".$type[$i].")";
}
?>
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.