This is a discussion on PHP to return custom error messages from MySQL within the alt.comp.lang.php forums, part of the PHP Programming Forums category; Hi, I have a database which has two fields which must contain unique date. At the moment I am currently ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Hi,
I have a database which has two fields which must contain unique date. At the moment I am currently using mysql_error() to return the error message. And this returns "Duplicate entry 'aaa' for key 2" and Duplicate entry 'bbb' for key 3". I know what each key means but how can I send a custom error message say field x is already registered on our system please try again? Many thanks in advanced. |
|
|||
|
Iain wrote:
> Hi, > > I have a database which has two fields which must contain unique date. > > At the moment I am currently using mysql_error() to return the error > message. And this returns "Duplicate entry 'aaa' for key 2" and > Duplicate entry 'bbb' for key 3". I know what each key means but how > can I send a custom error message say field x is already registered on > our system please try again? > > > Many thanks in advanced. Rather than just error-handling, you could add the IGNORE keyword to your INSERT query, i.e. INSERT IGNORE INTO table (aaa, bbb) VALUES ($valA, $valB) Then look at mysql_affected_rows(). If it returns zero, the row was not added, so you could then do something like: SELECT COUNT(*) FROM table WHERE aaa=$valA If COUNT(*) is non-zero, it was aaa that was the duplicate key, otherwise it was bbb. Not particularly elegant, but IMO more elegant than causing an error and then substring matching on the error string (the only real alternative I can see at the moment). -- Oli |