CyberJunkie
CyberJunkie

Reputation: 22674

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

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?

Upvotes: 1

Views: 9574

Answers (5)

Hassan Saeed
Hassan Saeed

Reputation: 7080

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

Upvotes: 0

Toihid
Toihid

Reputation: 1

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

Upvotes: 0

sdolgy
sdolgy

Reputation: 7001

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.

Upvotes: 1

Noah Duncan
Noah Duncan

Reputation: 510

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.

Upvotes: 5

Jason McCreary
Jason McCreary

Reputation: 72961

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.

Upvotes: 5

Related Questions