1

I am using UNIQUE Constraint in my table for two columns to prevent duplicate rows. If I try to insert a row with the same 2 columns I get

A Database Error Occurred Error Number: 1062

Duplicate entry '62-88' for key 'subscription'

INSERT INTO subscriptions (user_id, subscribed_to, date) VALUES ('62', '88', '2011-07-11 19:15:13')

Filename: C:\wamp\www\mysite\system\database\DB_driver.php

Line Number: 330

How can I return a php error, e..g Already subscribed! instead of displaying the mysql error?

1

5 Answers 5

5

Call mysql_errno() after your mysql_query() and check for 1062.

Note: It's a more common/intuitive solution to query the database first. See answer by Manocho.

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

4 Comments

+1: The fewer trips between the database & the application, the better.
Thanks for the suggestion! I'm using an MVC pattern. If I understood correctly, I add mysql_errno() after my insert query (in my model) and that should return 1062? Then I would use if ($query == 1062) display error?
Yes. You could put it in your Model. But I'd argue this is business logic and it may be better served in your Controller. Note, check if mysql_errno() returns 1062, not the query.
Where is the answer by Manocho?
5

I think you will need to run a query manually to check if the entry already exists in your database. so something like: SELECT COUNT(*) FROM subscriptions WHERE (user_id = '62' AND subscribed_to = '88'). If the count returned is > 0 then return the error, however you want it displayed.

2 Comments

@Jason 's response is actually more efficient than mine, though both would work.
The fewer trips between the database & the application, the better.
1

Using the 3rd link, compare the mysql error or mysql errno to the list of errors and if the condition is met, provide your alternate error message.

Comments

0

To solve the error you can do this:

mysql_query($sql);

if (mysql_errno() == 1062) {       
  print "<script type=\"text/javascript\">"; 
  print "alert('The informations are already inserted')"; 
  print "</script>";
}

Comments

0

try this code :

  $query = "INSERT INTO ".$table_name." ".$insertdata;
                if(mysqli_query($conn,$query)){
                    echo "data inserted into DB<br>";                   
                }else{
                   if(mysqli_errno($conn) == 1062)
                       echo "duplicate entry no need to insert into DB<br>";
                   else
                    echo "db insertion error:".$query."<br>";

                }//else end

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.