1

I am trying to follow the following blog and use an UPDATE, IF, INSERT INTO statement seeing that it will no go over my data twice.

Please note it is for php.

The statement that I have is as follows

$query = "UPDATE 
            " . $this->table_name2 . "
        SET  
            batch = :batch, 
            created = :created
        WHERE 
            id = :id
        IF row_count() = 0 
        INSERT INTO " . $this->table_name2 . "
        SET 
            id=:id, 
            batch=:batch, 
            created=:created";

But my return value always comes back as false, and I do not know where the problem is.

If I try the first half of the statement it updates the information:

$query = "UPDATE 
            " . $this->table_name2 . "
        SET  
            batch = :batch, 
            created = :created
        WHERE 
            id = :id

And if I try the second half of the statement it INSERTS the information:

        INSERT INTO " . $this->table_name2 . "
        SET 
            id=:id, 
            batch=:batch, 
            created=:created";

I do not find any help after allot of searching so far, and I feel that somehow my IF statement may not be correct, but I do not even get info on the IF row_count() = 0 in the docs.

3
  • If can only be used in stored procedures, not as part of SQL statements Commented Oct 24, 2017 at 8:26
  • @ JochenJung O ok, there is something else that I have to learn then. What alternative statement would you suggest I use that will be the quickest if you don't mind? Commented Oct 24, 2017 at 8:33
  • You are maybe looking for the on duplicate key update version of the insert statement. Commented Oct 24, 2017 at 8:44

1 Answer 1

1

The IF statement is available in stored procedures only.

If id is the primary key (or unique) this should work for you:

INSERT INTO " . $this->table_name2 . "
       SET
            id = :id, 
            batch = :batch, 
            created = :created
ON DUPLICATE KEY UPDATE
            batch = :batch, 
            created = :created

This will execute the INSERT statement only, of the ID does not exits yet. If it already exists, it will execute the UPDATE part.

Sign up to request clarification or add additional context in comments.

3 Comments

That is exactly what I was looking for, thank you very much!!
Hi JochenJung, I just changed the quotes after the first created = :created to after the second created = :created to make it work. Regards
You are right, they do not belong there. Just fixed it in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.