3

I have a MySql query, and I am trying to check if there was a duplicate entry in my PHP code, and I am trying to do something like this:

if(!$result)
{
    $error_message = mysql_error();

        $pos = strpos ( $error_message ,  'Duplicate entry' );

        if($pos === false)
        {
           ... Do some error reporting...

but the line $error_message = mysql_error(); seems to be breaking it. Would someone know why that happens and how to detect a duplicate error message correctly since this is a bit of a hack on my part?

5
  • 5
    just to warn you before you get too much code written: the mysql_xxx() functions that you're using here are considered obsolete, and are not recommended for use. The PHP manual strongly recommends using either the `mysqli_xxx() functions (which are very similar, but newer and supports more features), or the PDO library (which is quite different but a lot more powerful). Commented Sep 16, 2012 at 16:11
  • @spudley thank you, didn't realize that! So I should just change all my functions to mysquli instead of mysql? Commented Sep 16, 2012 at 16:14
  • 1
    it's not quite as simple as adding i all over, but it's not far off, at the basic level. Commented Sep 16, 2012 at 16:27
  • also, while you're making the switch, it's worth mentioning that one of the major features in the newer libraries is 'Parameterised queries', which allows you to make your queries secure without having to escape all your strings. It's not compulsory, but if you can convert to using that at the same time, it'll be a big win for your code quality. Commented Sep 16, 2012 at 16:40
  • To check if an entry would be a duplicate, no, don't try to parse the text of the database error. Either, get the error number, which is a much better way to test for the issue, or do a SELECT first on a locked table, then the INSERT, inside a transaction. Commented Sep 16, 2012 at 18:06

2 Answers 2

3

You could use mysql_errno, or mysqli_errno, and look for the error number 1062, which is the error number for duplicate entries.

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

Comments

2

You should look at the behaviour of MySQL's INSERT IGNORE It will allow you to tell MySQL that you're doing an insert where there might be a duplicate, and if so, don't do anything.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.