I want to add product in multiple categories in php. After lot of search/research on this I am able to add products in multiple categories but its not working while updating/changing product categories on update page .
MY DB structure is as:
PRODUCTTABLE
_____________________________________________
| pid | pname | price | pdetails |
-----------+---------------+-------+----------+
CATEGORYTABLE
______________________________________
| id | catname | catslug |
-----------+---------------+----------+
PRODUCT2CAT
____________________________
| product_id | cat_id |
-----------+----------------+
Code used on ADD PRODUCT page:(only relevent to question)
<form method="post">
...........
echo "<input type=\"checkbox\" name=\"pcateg[]\" value=\"$catid\" /> $catnm<br />";
...........
if(isset($_POST["submit"])) {
.........
.............
$pc2=$_POST["pcateg"];
$query1 = "insert into producttable(pname,price,image,pdetails) values('$pn','$p','$img','$pd')";
mysql_query($query1);
$prdid = mysql_insert_id();
foreach($pc2 as $key=>$values)
{
$query2 = "INSERT INTO product2cat(product_id,cat_id) VALUES('$prdid','$values') ";
$result2 = mysql_query($query2);
}
}
When I Add Product, code is working well and insert selected categories ID in PRODUCT2CAT table.
Code used on UPDATE PRODUCT Page is:
<form method="post">
...........
while($ans=mysql_fetch_array($cresult))
{
$selected = "";
$catId = $ans['id'];
$catNm = $ans['catname'];
if ($catId == $categ) {
$selected = "checked";
}
echo "<input type=\"checkbox\" name=\"pcateg[]\" value=\"$catId\" $selected /> $catNm<br />";
}
........
if(isset($_POST["submit"])) {
.........
.............
$query1="UPDATE producttable SET pname='$pn', price='$p', image='$img', pdetails='$pd' WHERE pid=$prid";
mysql_query($query1);
foreach($pc2 as $key=>$values)
{
$query2 = "UPDATE product2cat SET cat_id='$values' WHERE product_id=$prid";
$result2 = mysql_query($query2);
}
}
Update $query2 is not working.
Or I have to use 2 queries 1st to delete old records and then insert new record. How to use query in such situation so as to del/update selected categories on product update.
I also want to display old categories as preselected checkbox on update page. $selected = "checked" It works on single category But how to do this in multiple check.
$pc2query