简体   繁体   中英

How to check if the data already exists in the database?

How to check if the data($chassis, $pin) already exists in the database and if it does I want it to throw an error back saying "User exists". I'm using json to display errors and right now using the below code the data gets inserted even if the chassis and pin already exists in the database.

<?php
session_start();

require("config/config.php");
date_default_timezone_set('Asia/Calcutta');
if (isset($_POST['user_submit']))
    $chassis = mysql_real_escape_string($_POST['chassis']);
$pin           = mysql_real_escape_string($_POST['pin']);
$title         = mysql_real_escape_string($_POST['title']);
$fname         = mysql_real_escape_string($_POST['fname']);
$lname         = mysql_real_escape_string($_POST['lname']);
$email         = mysql_real_escape_string($_POST['email']);
$mobile        = mysql_real_escape_string($_POST['mobile']);
$dob           = mysql_real_escape_string($_POST['dob']);
$anniversary   = mysql_real_escape_string($_POST['anniversary']);
$company       = mysql_real_escape_string($_POST['company']);
$designation   = mysql_real_escape_string($_POST['designation']);
$home_business = mysql_real_escape_string($_POST['home_business']);
$add1          = mysql_real_escape_string($_POST['add1']);
$add2          = mysql_real_escape_string($_POST['add2']);
$city          = mysql_real_escape_string($_POST['city']);
$state         = mysql_real_escape_string($_POST['state']);
$pincode       = mysql_real_escape_string($_POST['pincode']);
$date          = date('y.m.d h:i:s A');

$hostname = '';
$database = '';
$username = '';
$password = '';

$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
    $json['error'] = "Unable to Connect server!" . mysql_error();
}
if (empty($json)) {
    mysql_select_db($database) or die("Unable to select database!" . mysql_error());
    $sql = mysql_query('SELECT chassis,pin FROM checking_chassis WHERE chassis="' . $chassis . '" && pin="' . $pin . '" ');

    if (mysql_num_rows($sql) == 1) {

        $sql1 = mysql_query('SELECT chassis,pin FROM taj_contact_info WHERE chassis="' . $chassis . '" && pin="' . $pin . '" ');
        if (mysql_num_rows($sql1) == 1) {
            $json['error'] = "User already exists";
            exit();
        } else {
            $query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,date_added) VALUES("' . $chassis . '","' . $pin . '","' . $title . '","' . $fname . '","' . $lname . '","' . $email . '","' . $mobile . '","' . $dob . '","' . $anniversary . '","' . $company . '","' . $designation . '","' . $home_business . '","' . $add1 . '","' . $add2 . '","' . $city . '","' . $state . '","' . $pincode . '","' . $date . '")';

            $sql1 = mysql_query($query);

            $message = "Thank you for registering. You can indulge in the fine dining experience with the Taj gift certificate, which will reach you within 30 days. Team Purple Club";

            $sms = "http://bulkpush.mytoday.com/BulkSms/SingleMsgApi?feedid=340479&UserName=&password=&sendername=PURPLE&To=" . $mobile . "&message=" . urlencode($message) . "";

            $work = file_get_contents($sms);

            $json['success'] = "Successfully inserted";
        }
    } else {
        $json['error1'] = "Please enter valid chassis number and pin";

    }

}

echo json_encode($json);
?>

Javascript

<script type="text/javascript">
    $(document).ready(function (){

        $("#user_submit_form").submit(function(){
            var user_data = $("#user_submit_form").serialize();

                                var mobile = new Array();                                                            
                                                mobile = $('#mobile').val().split("");

                                                var pincode = new Array();                                                          
                                                pincode = $('#pincode').val().split("");

                                                if($('#chassis').val() =='')
                                                {                                              
                                                                                alert('Please enter chassis');
                                                }              
                                                else if ($('#pin').val() =='')
                                                {                                              
                                                                                alert('Please enter pin');
                                                }


                                                else        {

                                                                                $.ajax({
                                                                                type                                                            : "post",
                                                                                url                                                             : "validate_user.php",
                                                                                data                                                            : user_data,
                                                                                dataType                                                        : "json",
                                                                                success: function(json){

                                                                                                if(json.error)
                                                                                                {
                                                                                                                alert(json.error)
                                                                                                }
                                                                                                else if(json.error1)

                                                                                                {
                                                                                                                alert(json.error1)

                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                                alert(json.success)
                                                                                                                /*location.reload();

                                                                                                                window.location="http://clps.cequitysolutions.com/taj/thankyou.php";*/

                                                                                                }
                                                                                }


                                                                                });


                                                                                }
        });                   

                });
      function validateEmail(email) 
                {
                                var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;                                                                                            
                                return re.test(email);
                }
</script>

I would say you should create unique indexes for chassis and pin . Avoiding duplicates is exactly why unique indexes exists :

alter table taj_contact_info add unique index(chassis, pin)

Now you can run your insert query safely :

$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,compa ...

and after that check if a record has been inserted :

if (mysql_affected_rows()>0) {
  //success
} else {
   $json['error'] = "User already exists"
}

If mysql_affected_rows returns -1, the insert script has failed. That would happend if (I guess) chassis is not valid, like an empty string.

Make a unique index for both columns on the taj_contact_info table.

ALTER TABLE taj_contact_info ADD UNIQUE INDEX uniqueindex ( chassis,pin )

and after in php when you try to insert as normal, you will get a duplicate key error which you can handle in php...

$sql = "insert into taj_contact_info set chassis='1234', pin='12345',etc...";
$result = mysql_query($sql);
if (!$result) {
    if (mysql_errno() == 1586) {
        echo "ID is already in the database, user exists";
    } else {
        die('Invalid query: ' . mysql_error());
    }
} else {
    echo "All cool, user inserted.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM