-1

I am struggling a bit with something that I think should be simple to solve.

I first check the database to see if it exists. I would like it to insert the date if it does not exist but I am not sure how to structure the IF statement part. Many thanks

$date='2017-05-13';
$select_date = mysqli_query($link, "SELECT * from `marker` WHERE `date`='$date' ");

$insert_date = mysqli_query($link, "INSERT INTO `marker` (`date`,`value`) VALUES ('$date','1') ");
Jean-Claude
  • 115
  • 1
  • 3
  • 13

1 Answers1

1

In general, for this type of operation, you want to use on duplicate key update. This starts with a unique index:

CREATE UNIQUE INDEX unq_marker_date ON marker(date);

Then the database guarantees only one row per date. You can then do the insert as:

INSERT INTO `marker` (`date`, `value`)
    VALUES ('$date', '1')
    ON DUPLICATE KEY UPDATE `date` = VALUES(`date`);

The ON DUPLICATE KEY part does nothing except prevent an error for a duplicate date.

Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624
  • Thanks i've implemented this and it works as required. It is a shame that my question has been down voted because the others thought it was too simple. Thanks again for this code! – Jean-Claude May 19 '17 at 10:05