Solved

Check database for duplicate entries

Posted on 2014-03-03
10
528 Views
Last Modified: 2014-03-04
I am trying to find a way to check for duplicate entries in a mysql database. When I say duplicate, if the value already exists in a table, then deny the entry.

I am using jquery to connect to php and would appreciate some guidance as to how I can possibly code this. I have tried various if statements, but all error or fail miserably. I have posted the relevant part of the code as all other areas ie; validation are working ok. Also assume, all db calls and connections are in place. Thanks

submitHandler: function()   {
                if ($("#USRboxint").valid() === true)  { 
                var data = $("#USRboxint").serialize() + '&submit=true';
                $.post('/domain/users/boxesadd.php', data, function(msgs) {

               var messageOutputs = '';
                for (var i = 0; i<msgs.length; i++){

                    messageOutputs += msgs[i].box+'  ';
                    //console.log(messageOutputs);    
                }

                $("#USRboxint").get(0).reset();

                var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your entry successfully submitted.<br /><br />Thank you.</b>');
                   $dialog.dialog({
                   autoOpen: true,
                   modal: true,
                   title: 'New Entry successfull',
                   width: 400,
                   height: 200,
                   draggable: false,
                   resizable: false,
                   buttons: {
                   Close: function() {
                   $( this ).dialog( "close" );
                   }
                   }
                   });


                }, 'json');

         } else

         { 
           return; 
         }
        },
        success:    function(msg)   {

        }

Open in new window


PHP Code

<?php

         $status = mysql_real_escape_string($_POST['status']);
         $company = mysql_real_escape_string($_POST['company']);
         $requested = mysql_real_escape_string($_POST['requested']);
         $activity = mysql_real_escape_string($_POST['activity']);
         $address = mysql_real_escape_string($_POST['address1']);
         $service = mysql_real_escape_string($_POST['service']);
         $box = mysql_real_escape_string($_POST['box_add']);
         $date = DateTime::createFromFormat('d/m/Y', $_POST['datepicker']);
         $destdate = $date->format('Y-m-d');
         $authorised = mysql_real_escape_string($_SESSION['kt_name_usr']);
         $submit = mysql_real_escape_string($_POST['submit']);
         $dept = mysql_real_escape_string($_POST['dept']);

         $array = split('[,]', $_POST['box_add']);

         if (isset($_POST['submit'])) {

          $form = array();
          foreach ($array as $box) {


          // **check for dupe here**

         $form[] = array('dept'=>$dept, 
                     'company'=>$company,
                     'address'=>$address,
                     'service'=>$service,
                     'box'=>$box,
                     'destroydate'=>$destroydate,
                     'authorised'=>$authorised,
                     'submit'=>$submit);

    $sql = "INSERT INTO `temp` (service, activity, department, company, address, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$dept', '$company', '$address', '$requested', '$destdate', NOW(), '$box', 1)";
    $result = runSQL($sql) or die(mysql_error());
          }

       } 
       $result=json_encode($form);

         echo $result;
?>

php jquery 

Open in new window

0
Comment
Question by:peter-cooper
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39900073
Firstly, which part of your record identifies it as a duplicate? i.e which field needs to be unique in your database.

Normally the way you do this is to set a UNIQUE index on the particular field in your table. When you then try and insert the record in PHP, the database will automatically fire an error with a code of 1062. You then check for this error an act accordingly:

mysql_query(yourInsertStatement);
if (mysql_errno() == 1062) {
   //you have a duplicate
}
0
 

Author Comment

by:peter-cooper
ID: 39900089
Hi Chris

The record in question is the field 'item'.  I am not familiar at all with this way of working.  How would I amend my db to accept this 'UNIQUE' entry? Thanks
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39900117
Peter,

Several ways to do it depending on how you manage your database, but basically you run this query:

ALTER TABLE temp ADD UNIQUE (item);

If you're using phpMyAdmin, select your 'temp' table, then the Structure tab. click on the Unique button for the 'item' column.
0
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 

Author Comment

by:peter-cooper
ID: 39900146
Only problem I foresee with that approach chris, is would I not need 2 entries for the sql query. 1 for the item and 1 for the rest or can I incorporate your suggestion as 1 query. Thanks
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39900151
Not sure I follow.

You run the ALTER TABLE query once - now! And the unique constraint is permanently added to your table.

Then in your PHP script, you just run as normal, but whenever you try to insert a record that contains a duplicate 'item', error 1062 would be raised.
0
 

Author Comment

by:peter-cooper
ID: 39900165
Ok at the moment I have this query:

$sql = "INSERT INTO `temp` (service, activity, department, company, address, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$dept', '$company', '$address', '$requested', '$destdate', NOW(), '$box', 1)";

How do I adapt your code to include to also insert the other values. ie; does it become

$sql = "ALTER TABLE temp ADD UNIQUE (item) (service, activity, department, company, address, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$dept', '$company', '$address', '$requested', '$destdate', NOW(), '$box', 1)";

Open in new window

which I know is incorrect. Thanks
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39900184
No. On your database, using a tool such as phpMyAdmin, you run the ALTER TABLE query. You only do that once - do it now! Once that's done, your table will have a unique constraint on it permanently - job done! It has nothing to do with your PHP script.

After that's done, you adapt your PHP to catch the 1062 error:

$sql = "INSERT INTO `temp` (service, activity, department, company, address, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$dept', '$company', '$address', '$requested', '$destdate', NOW(), '$box', 1)";
mysql_query($sql);
if (mysql_errno() == 1062) {
   //you have a duplicate
} else {
   //you don't have a duplicate
}

Open in new window

As an aside, at some point in the very near future you are going to have to change your code from using the mysql library to using the PDO or mysqli library - the mysql library is deprecated and will be removed from PHP altogether.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39900246
An article showing how to make the required move away from the deprecated MySQL extension is available here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

A page mapping the familiar but deprecated MySQL_xxx() functions to the modern extensions is available here:
http://www.iconoun.com/mysql_mysqli_pdo_function_map.php

In my experience there are some things that can help you make this conversion smoothly. It is quite OK to make two simultaneous connections to the DB server, so you can keep the existing MySQL connection and add a MySQLi connection.  Once you have done that you can convert the PHP code one query at a time.  The PHP syntax is easiest if you use object-oriented MySQLi as shown in the article.
0
 

Author Closing Comment

by:peter-cooper
ID: 39900400
Thanks very much Chris. Helpful as usual.
0
 

Author Comment

by:peter-cooper
ID: 39900403
Thanks Ray. Will check it out.
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question