Re: DB and INSERT's allready exists?

From: Date: Wed, 13 Jul 2005 17:04:27 +0000
Subject: Re: DB and INSERT's allready exists?
References: 1 2 3  Groups: php.pear.general 
Request: Send a blank email to pear-general+get-19976@lists.php.net to get a copy of this message
On 7/13/05, Martin Klaffenboeck <martin.klaffenboeck@gmx.at> wrote: > Am Mittwoch, den 13.07.2005, 11:53 +0200 schrieb Klaus Guenther: > > The easy way is... first do a SELECT to see if there is a match before > > trying to insert. > > > > I assume you're using DB? Then you might also be able to check for the > > error on insert and look at the error code and based on the error do > > what you want. However, trying to insert bad info into the database > > isn't very wise, imho. I'd anyway first do the select :) > > But why? I thought thats what INSERT is for, otherwise we would not > need INSERT and REPLACE, one of it would be enaugh. So I think I use > INSERT and catch the error. > > Doing a select before inserting would make more queries, and I think it > would slow down the process of my script. > Why? Because it's always good sense to check for all possible errors before processing your data. However, even if you do the select it's still possible for an error to happen (say two people register with the same e-mail at the same moment in time, the selects will go through fine, one user will register, the other will get an INSERT error). You should be checking for an error return from whatever DB abstraction layer you're using. Assuming DB: $ret = $db->query('INSERT INTO users (email) VALUES ('.$db->quoteSmart($emailAddress).')'); if (PEAR::isError($ret)) { if ($ret->getCode() == DB_ERROR_CINSTRAINT) { echo 'This email address has been used before'; } else { echo 'There has been an error'; mail('admin@example.com', 'Error in user insert', print_r($ret, true)); } } else { //go on } > > > hth, > > Klaus > > > > On 7/13/2005 10:10 AM, Martin Klaffenboeck spake the following words: > > > > >Hello! > > > > > >I'm using an insert statement to register new users. Now I set a mysql > > >'Email' field unique so that an user cannot register twice. > > > > > >But how can I check if the INSERT failed because of an unique? I want > > >to tell the user he's allready registerd and ask to send a new password. > > > > > >How can I do that? > > > > > >thanks, > > >Martin > > > > > > > > > > > > -- Justin Patrin

« previous php.pear.general (#19976) next »