An array creates by this:
<input type="checkbox" name="transport[]" value="0">Taxi
<input type="checkbox" name="transport[]" value="1">Bus
<input type="checkbox" name="transport[]" value="2">Train
Although the checkbox only comes if its true(if its checked), so only the checked checkboxes will be passed.
Now I am trying to do so that the checkboxes that gets passed(the ones that are checked), should insert a row in table transports and the checkboxes that are not checked(not gets passed) should delete. And if it already is inserted, it should not do anything.
So:
- Check if its already inserted before
- Insert new row in transports
for the checkboxes passed - Delete the
rows for the checkboxes that didnt
pass
I tried doing this:
$transport = $_POST["transport"]; // variable receiving
for($u=0; $u<3; $u++){ // taxi, bus and train (3)
if($u == $transport[$u]){
$alreadyExists = $connect->prepare("SELECT id FROM transport WHERE xID=:xID AND transport=:t");
$alreadyExists->bindValue(":t", $u);
$alreadyExists->bindValue(":xID", $cID);
$alreadyExists->execute();
$alreadyExists = $alreadyExists->rowCount();
if($alreadyExists == 0){ // if it doesnt exists, insert into
$updateTransport = "INSERT INTO transport (xID, transport) VALUES (:id, :t)";
$updateTransport = $connect->prepare($updateTransport);
$updateTransport->bindValue(":id", $cID);
$updateTransport->bindValue(":t", $u);
$updateTransport->execute();
}
}else{ // delete row as it is not checked
$updateTransport = "DELETE FROM transport WHERE xID=:id AND transport=:t";
$updateTransport = $connect->prepare($updateTransport);
$updateTransport->bindValue(":id", $cID);
$updateTransport->bindValue(":t", $u);
$updateTransport->execute();
}
}
But It wont work properly, I receive undefined offset 2, 1 I cant figure out why
What have I done wrong? How can I make it work properly?
you should do somethign like:
and