I'm building a simple signup application on my website with user database. I'm using PHP and MySQL. I want take in "username" and "email". Both are primary keys in my database. I obviously don't want the same of either. How can I provide feedback to the user if a) the username is already taken and b) the email is already used. I know I can do a query on both but I thought this may be redundant (2 searches and an insert). Is there a way to receive feedback from MySQL if I try to insert on a duplicate key. As in, this it he field that failed on the insert. If not, what i开发者_StackOverflows the best way/practice to do this?
Thanks all.
The best you can do is execute the below:
$result = mysql_query( "insert into yourtable (`username`, `email`) values ('usernamesubmitted','emailsubmitted')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
The assumption here is that the insert query will fail if one of the fields to be inserted is a primary key and is being duplciated. In which case....output a message- the message will contain the max info you could get in this situation, you can then handle it as appropriate
精彩评论