Hi guys, I have a php code that displays a list of dishes where a user can check on those dishes and then save the selection to the database. My code works find when selecting and saving the data. But the problem is that when I try to uncheck one of the dishes that is previously been saved, it won't remove the unchecked dish in the database.
Here is the class file I am using:
class.php
<?php
class Food {
private $_con;
function __construct(){
$this->_con = mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('food', $this->_con) or die(mysql_error());
}
function getDishes(){
$query = 'SELECT * FROM dish';
$result = mysql_query($query);
$data = array();
if($result){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
return $data;
}
}
function getPersons(){
$query = 'SELECT * FROM person';
$result = mysql_query($query);
$data = array();
if($result){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
}
return $data;
}
function getPersonData($personID){
$query = 'SELECT * FROM person WHERE personid='.$personID;
$result = mysql_query($query);
$data = array();
if($result){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
}
return $data;
}
function insertPersonDish($personID, $dishID){
$query = 'SELECT * FROM persondish WHERE personID='.$personID.' AND dishid='.$dishID;
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
return true;
} else {
$insert = 'INSERT INTO persondish(personid, dishid) VALUES('.$personID.','.$dishID.')';
$result = mysql_query($insert);
return mysql_insert_id();
}
}
function deletePersonDish($personID, $dishID){
$query = 'DELETE FROM persondish WHERE personid='.$personID.' AND dishid='.$dishID;
return (mysql_query($query));
}
}
And here is my view file:
view.php
<?php
require_once 'class.php';
$food = new Food;
$dishes = $food->getDishes();
$persons = $food->getPersons();
if(isset($_POST['choices'])){
$personID = $_POST['personID'];
foreach ($dishes as $dish) {
$checked = false;
if(isset($_POST['food'])){
$checked = true;
foreach ($_POST['food'] as $key => $value) {
echo 'Inserting Record ID: '.$food->insertPersonDish($_POST['personID'], $value).' with dish ID: '.$value.'<br />';
}
} else {
$checked = false;
}
if(!$checked){
$food->deletePersonDish($_POST['personID'], $dish['dishid']);
echo 'Removing Data from person ID: '.$_POST['personID'].', Dish ID: '.$dish['dishid'].'<br />';
}
}
}
?>
<form method="post">
<p><select name="personID">
<?php
foreach ($persons as $person) {
?><option value="<?php echo $person['personid']; ?>"><?php echo $person['personname']; ?></option><?php
}
?>
</select></p>
<?php
foreach($dishes as $dish){
?><input type="checkbox" name="food[]" value="<?php echo $dish['dishid']; ?>" /><?php echo $dish['dishname']; ?><br /><?php
}
?>
<input type="submit" name="choices" value="Choose" />
</form>
Do you have any idea how to solve this? Thanks