0

In PHP PDO trying to use SELECT COUNT(*) SQL to see if primary key exists (so then can update rather than insert),

When I call the function sqlCall; fetchColumn() returns 0 or 1 depending on if it exists or not, however when it is returned it always returns false?

How do I get it to return if row exists or not?

Thanks for help!!

 function sqlCall($primary) {

            $sql = $handler->prepare("SELECT COUNT(*) FROM  WHERE ". strtolower($primary)."=:".$primary);

            $sSqlParams = array(':'.$primary => $primary);

            $sql->execute($sSqlParams);


            if($sql->fetchColumn()==1){
                return 1;

            } else {
                return 0;
            }
            break;
}




try {
                $rows = sqlCall($primary);

                if($rows=True){
                    //UPDATE SQL
                } else {
                    //INSERT SQL
                }
}
catch(PDOException $er) {

                    die();
}
1
  • 1
    what are you trying to do here? WHERE ". strtolower($primary)."=:".$primary is your $primary the same as your column name? Commented Jul 19, 2016 at 0:19

1 Answer 1

1

You are going about this wrong way - there is MySQL construct which allows you to do this without any need for workarounds. If you would like to update record if exists and if not insert it than use: INSERT ... ON DUPLICATE KEY UPDATE

It goes like this:

INSERT INTO table (primary_key, field_to_update) VALUES(primary_key_value, value_to_update) ON DUPLICATE KEY UPDATE field_to_update = value_to_update

Whenever your primar_key will be already in database the record will be updated and if primary_key does not exists than new record will be created.

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

1 Comment

Thank you! I will try this later on :)

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.