开发者

Display error message in php for MYSQL duplicate error

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

开发者_如何学Python

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?


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.


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.


  • http://php.net/manual/en/function.mysql-error.php I assume you are able to programatically obtain the MySQL error
  • http://www.php.net/manual/en/function.mysql-errno.php
  • http://dev.mysql.com/doc/refman/5.5/en/error-handling.html

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.


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>";
}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜