php2014 Posted March 25, 2014 Share Posted March 25, 2014 Hello all, I'm working on a project where I have 3 tables : - test - category - link_category_test In test I have columns id, name. In category I have the columns id, name. In link_test_category I have columns test_id, category_id. When I add an item to table test I can select which categories it will belong too. It can be multiple categories. The connection between those 2 tables is stored in link_test_category. That I get to work. But now I want to be able to edit the categories connected with an item, with checkboxes. This means I'll have a list of all categories and for the categories which are connected with the item, the checkboxes are checked. The rest is unchecked. As soon as I check them they should be added to the many to many relationship table link_test_category, if they are unchecked and before where checked I want them deleted. I have the following code for creating a new item : new.php <form method="post" action="new_add.php"> <table><tr><td> <input name="name" id="name"> </td></tr></table> <table> <?php $query=mysqli_query($conn, "select * from category") or die (mysqli_error($conn)); while($row=mysqli_fetch_array($query)){ $category_id=$row[íd]; ?> <tr> <td><input name="selector[]" type="checkbox" value="<php echo $category_id; ?>"></td> <td><?php echo $row['name'] ?></td> </tr><?php } ?> </table> <input name="save" type="submit" id="save"> </form> new_add.php <?php $name = $_POST['name']; sql = "INSERT INTO test (id, name) VALUES (NULL, '{$name}');"; $retval = mysqli_query($conn, $sql); if(! $retval ) { die('Could not enter data ' . mysqli_error($conn)); } $insert_id = mysqli_insert_id($conn); $id=$_post['selector']; $N = count($id); for($i=0; $i < $N; $i++) { $result = mysqli_query($conn, "SELECT * FROM category where id='$id[$i]'"); while($row = mysqli_fetch_array($result)) { $sql = "INSERT INTO link_category_test (category_id, test_id) VALUES ('{ $insert_id}', '{$row['id']}');"; $retval = mysqli_query($conn, $sql); if(! retval ) { die('Could not enter data '. mysqli_error($conn)); } } } ?> Link to comment https://forums.phpfreaks.com/topic/287271-edit-many-to-many-relationship-with-checkbox/ Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.