Yamaha32088
Yamaha32088

Reputation: 4163

MySQL IF THEN ELSE statement

I am having a terrible time understanding the MySQL documentation on using the IF statements I am hoping someone can simplify it for me. I don't even know if what I want to accomplish is best done using the MySQL IF statements or if there is a better way to do it using PHP. I am attempting to create an online time card system just for learning/experimenting for now. I have three buttons "Clock in" "Update" and "Clock Out". "Clock in" is pretty straight forward all I do is add "Employee ID" and "Time in" along with "Date" to the table. The "Update" function is where I am at now. So what I am looking to do with it is:

  1. Add several PHP variables to specified columns in table.
  2. Add the current time to the "time out" column.
  3. Add the current time to the "time in" column in a new row with same "employee ID".

So the statement I want to make is going to be something like:

IF "timeOut" is NULL
WHERE "employeeID" AND "currentDate"
THEN 
UPDATE "timeRecords" SET "jobDescription", "timeOut"
WHERE "employeeID" AND "currentDate"
THEN
INSERT "timeIn", "employeeID", "currentDate"

Is there even a way to write this in MySQL? If so could someone give me an example of a working MySQL statement the documentation does not provide enough for me to understand it. Maybe there is a better way to accomplish this I am missing?

Upvotes: 2

Views: 572

Answers (1)

paulsm4
paulsm4

Reputation: 121669

You really shouldn't be using if/then statements in your SQL at all. "control structurs" are for languages like C, PHP or Java -SQL is about "sets".

In this particular case, look at the mysql "Replace" statement. It's probably ideal for your scenario ("if new, then insert; else update"):

Upvotes: 3

Related Questions