0

Good Day,

Right now Im having a hard time figuring if is it possible to have an IF ELSE function inside an sql query. I want to DELETE a row with same location and name, then UPDATE if not exist.

      $sql = "IF EXISTS (SELECT * FROM location_tbl WHERE name = '$a' && location = 'Drawing Room')
                            DELETE FROM location_tbl WHERE name = '$a' 
                                ELSE
                                INSERT INTO location_tbl (id, name, datetime, location) VALUES ('', '$a' , NOW(),'Drawing Room')";

Thank you so much for your KIND HELP

3 Answers3

0

You can have IF ELSE in the SELECT part of SQL, not in the way you want it.

You can do what you need in 2 SQLs - delete and then insert.

In Oracle you can use MERGE statement which can conditionally INSERT, UPDATE and DELETE. Please see https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606

Salim
  • 2,046
  • 12
  • 13
0

I think using if-else is not necessary in your case. You can always delete the existing record first and then insert a new one. If the record does not exist in the table, the delete statement will not delete anything from the table.

0

One suggestion would be to run the if statement using php:

$result = $mysqli->query("SELECT * FROM location_tbl WHERE name = '".$a."' AND location = 'Drawing Room'"); 
if($result->num_rows > 0 ){
    $mysqli->query("DELETE FROM location_tbl WHERE name = '".$a."'");
} else {
    $mysqli->query("INSERT INTO location_tbl (id, name, datetime, location) VALUES ('', '".$a."' , NOW(),'Drawing Room')");
}
Blaise
  • 330
  • 1
  • 11