0

My plan is to update/insert existing/new records into a database from an external, i have the information set to go into the database, but cannot check if it exists already.

my first attempted at doing database stuff

    $link = resdb::connect();
    $q = "IF ( EXISTS ( SELECT * FROM property AS this WHERE this.name = $propertyname ) )"
         ."begin"
            // UPDATE PROPERTY IF IT EXISTS
            ."UPDATE property (name, propertylocation, propertyrating, propertytype)" 
            ."SET ($propertyname, $locationid, $ratingid, $typeid)"          
            ."WHERE name = $propertyname"
         ."end"
         ."ELSE"
         ."begin"
            ."INSERT INTO property (name, propertylocation, propertyrating, propertytype)" 
            ."VALUES ($propertyname, $locationid, $ratingid, $typeid)"
         ."end";
    $r = mysqli_query($link, $q);
    if($r > 0){
        return true;
    }

A unique id is made on completion of each row.

1 Answer 1

2

First create a unique index on the name column:

ALTER TABLE property ADD UNIQUE KEY(name)

Now you can use the MySql INSERT ... ON DUPLICATE KEY UPDATE...

INSERT property (name, propertylocation, propertyrating, propertytype)
VALUES ($propertyname, $locationid, $ratingid, $typeid)
ON DUPLICATE KEY UPDATE 
    propertylocation = VALUES(propertylocation),
    propertyrating = VALUES(propertyrating),
    propertytype = VALUES(propertytype)

Docs: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Don't forget to sanitize database inputs.

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

1 Comment

great easier than TSQL method. upvote and answered. thank you

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.