I'm a PHP and MySQL newbie, and the behavior of mysql_insert_id() has become a brick wall for me when one of the database fields is UNIQUE. Greatly simplified, I have 2 tables.
property table
PropertyID PK, AI
//many property descriptors
UserID FK to user table
user table
UserID PK, AI
email UNIQUE
password
After validation, I insert the user's email into the users table and see if the email is already present, and thus a returning user. If not present, it is inserted and is a new user.
$sql = "INSERT IGNORE INTO user ( email ) VALUES ( '$email' )";
//INSERT to a UNIQUE email causes an error & abort. With IGNORE, no INSERT happens (affected_rows=0)
$UserID = mysql_insert_id(); // is 0 if email exists in its UNIQUE field
if ( mysql_affected_rows() == 0 ) {//0 is existing user, else is new user}
This works fine to separate new and returning users, who get different messages later. And it sets up 2 logic channels - one to input the new password, and the second to check if the input password matches.
However, the UserID of a second entry by a user (or third, and beyond) is always 0, zero because the email field is UNIQUE. Thus I can't make useful queries in the property table against UserID because all returning user rows have UserID=0
Despite a lot of searching, I haven't found or figured out a solution. How can I get the real UserID, not the 0 return, into the property table for both new and returning users?
Try to be specific with responses. I don't follow general directions well in this area.