How i can make a php page that adds values and if the value already exists to deletes it instead?

How i can make a php page that adds values and if the value already exists to deletes it instead?
0

how i can make a php page that adds values to the database, and if the value already exist to delete it instead of add it?
I am trying to do it but i am making a mistake and it only “deletes values”.

<?php
require("database.php");
    if(empty($username) || empty($password)){
        echo "error";
    }else{
        $cdtitle=$_POST["cds"];
        $cdartist=$_POST["kal"];
        $query= 'SELECT FROM cds WHERE cdtitle=:cdtitle && cdartist=:cdartist';
        $result = $sql->prepare($query);
        $result->execute([":cdtitle" => $cdtitle, ":cdartist" => $cdartist]);
        $a = $result->fetchAll();

    if($a>0){
        $cdtitle=$_POST["cds"];
        $cdartist=$_POST["kal"];
        $query= 'DELETE FROM cds WHERE cdtitle=:cdtitle && cdartist=:cdartist';
        $result = $sql->prepare($query);
        $result->execute([":cdtitle" => $cdtitle, ":cdartist" => $cdartist]);
        $a = $result->fetchAll();
    echo "Deleted!";
    }else{
        $add = "INSERT INTO cds(username, cdtitle, cdartist) VALUES (:username, :cdtitle, :cdartist)";
        $result = $sql->prepare($add);
        $result->execute([":username" => $username ,":cdtitle" => $cdtitle, ":cdartist" => $cdartist]);
        $result->fetchAll();
        echo "Added!";
    }
}
?>

ok where is my mistake? how i can make it this way that it will add the data to the database if it doesn’t exists and it will delete the data from the database if it exist?
Thanks!

Hi, I’m not sure that this is the issue, but as far as I remember the fetchAll method from PDO return an array.
Instead of checking $a > 0, check that the size of the array is greater than 0 with count($a) > 0

i just tried that and it didn’t worked
when i var_dump that i got int(0)
what could it be?

Thanks for the reply!

You are inserting the value in db
checking the condition if the value exist or not (Yes it will exist as you have insert it)
Delete if exist (It will always perform delete as value exist)
insert if it does not exist(execution wont reach here)

You can try this
check the value exist in db before insert
if value exist return message with value already exist
else insert the value in db