1

For some reason my insert/update check only ever inserts. the value userID does have a value so i dont know what is up with this. Any ideas?

$result = mysql_query("SELECT * FROM users where userID = $userID ");
if (mysql_num_rows($result) > 0) {
   mysql_query("UPDATE users SET firstName='$firstName', lastName='$lastName', 
             birthday='$birthday', update='$today', accessToken='$accessToken', emailOne='$emailOne' WHERE userID='$userId'");
} else {
   mysql_query("INSERT INTO users (userID, firstName, lastName, birthday, updated, accessToken, emailOne ) 
               VALUES ('$userId', '$firstName', '$lastName','$birthday', '$today', '$accessToken', '$emailOne')");
}
4
  • Have you thought about putting this logic into a routine instead? May cause a good bit less of a headache, although I do not see the error here. Commented Jun 19, 2011 at 16:59
  • 1
    This needs basic debugging first. What does $userID contain? What happens if you run the query in phpMyAdmin or a similar tool? Commented Jun 19, 2011 at 17:00
  • 2
    How about escaping your queries while you're at it... Commented Jun 19, 2011 at 17:01
  • What DBMS? You're better off combining the two statements into a single MERGE statement. Commented Jun 19, 2011 at 17:13

2 Answers 2

4

You'd be far better off doing INSERT ... ON DUPLICATE KEY UPDATE. Your version is subject to race conditions. It's entirely possible that between the time you do the SELECT * and then attempt the update/insert queries, ANOTHER script has already inserted the same ID number and then your script breaks. This also reduces the database load by one query.

As well, unless you've passed all those variables in the query through mysql_real_escape_string(), you'll probably be getting a visit from Little Bobby Tables.

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

Comments

1

From the way you're inserting the records, it seems that your userId field is a varchar (or alphanumeric) field. So your query NEVER reads the data that matches it since it is searching for it as a numeric. You've got to re-write the first line as:

$result = mysql_query("SELECT * FROM users where userID = '$userID' ");

Hope it helps.

Comments

Your Answer

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