I am new to php & need little help here. I've following code to INSERT multiple checkbox values into a table for same ID:
on my form I have:
<input type="checkbox" name="subcat[]" value="Mech">Mech
<input type="checkbox" name="subcat[]" value="Ele">Ele
<input type="checkbox" name="subcat[]" value="Civ">Civ
<input type="checkbox" name="subcat[]" value="Air">Air
<input type="checkbox" name="subcat[]" value="BSL">BSL
I've checked "Mech", "Ele" and "BSL"
and PHP to insert:
$subcat = $_POST['subcat'];
for($i=0; $i<sizeof($subcat);$i++){
$sql1="INSERT INTO mst_scatadd (party_code,scid)
VALUES ('$pcode',$subcat[$i])";
mysql_query($sql1,$con);
}
db looks something like...
sctid | party_code | scid
---------------------------------
1 | 01S001 | Mech
2 | 01S001 | Ele
3 | 01S001 | BSL
4 | 01K207 | Main
Now, how can I retrieve these values from db to my form for the same ID and make them as checked if I want to edit the checkboxes?
Little help would be appreciated!!
Thanks in adv.
EDIT 1:
Hello again guys!
I've done with inserting and retrieving checkbox values using implode and explode and its working fine. Thanks to @Antoniossss for good suggession to keep checkboxes values as numbers(make sure the column in db should be VARCHAR) Thanks to @Barmar to explain use of explode & thanks to @MarkTWebsite to share idea of if-else
Code for inserting multiple checkbox values:
foreach ($_POST['subcat'] as $_subcat)
{
$checksub[] = $_subcat;
} $finalsub = implode(',', $checksub);
$sql="INSERT INTO vendor_mst(party_code, subcat) VALUES ('$pcode','$finalsub')";
My final code to retrieve checkbox values from db...
sql="SELECT * FROM vendor_mst WHERE party_code like '".$searchname."'";
$result=mysql_query($sql,$con);
while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
$checksub = explode(',',$row['subcat']);
}
if(in_array("1",$checksub))echo '<input type="checkbox" name="subcat[]" value="1" checked >Mech'; else echo '<input type="checkbox" name="subcat[]" value="1">Mech';
if(in_array("2",$checksub))echo '<input type="checkbox" name="subcat[]" value="2" checked >Ele'; else echo '<input type="checkbox" name="subcat[]" value="2">Ele';
if(in_array("3",$checksub))echo '<input type="checkbox" name="subcat[]" value="3" checked >Civ'; else echo '<input type="checkbox" name="subcat[]" value="3">Civ';
if(in_array("4",$checksub))echo '<input type="checkbox" name="subcat[]" value="4" checked >Air'; else echo '<input type="checkbox" name="subcat[]" value="4">Air';
if(in_array("5",$checksub))echo '<input type="checkbox" name="subcat[]" value="5" checked >BSL'; else echo '<input type="checkbox" name="subcat[]" value="5">BSL';
Thanks to stackoverflow!
VALUES ('$pcode',$saincat[$i])";should beVALUES ('$pcode',$subcat[$i])";SELECT scid FROM mst_scatadd where party_code = '01S001'