Jump to content
giannis196

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

Recommended Posts

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 value to the database if it doesn't exists and it will delete the value from the database if it exist?

Share this post


Link to post
Share on other sites

Query your table to initialize values then do your nested if statement.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...