在生成随机函数的 ID 后,如何使用 PHP 循环检查 mysql 数据库中是否存在 ID?

How to loop to check either the ID is exist or not in mysql database with PHP after a random function's id is generated?

我有一个名为 Customers with Unique ID 的数据库,所以每次从 php 插入数据库时​​,我都需要通过随机函数为新客户生成一个新 ID,但我需要检查该 ID生成的是否存在于数据库中。

这是php随机函数:

function randomDigits($length){
    $digits = "";
    $numbers = range(0,9);
    shuffle($numbers);
    for($i = 0;$i < $length;$i++)
       $digits .= $numbers[$i];
    return $digits;
}

我试过像这样传递随机长度:

    $cusid = randomDigits(10);
    $generate_customer_id = "";

    $query_customer_id = dbQuery("SELECT customer_id FROM customers WHERE customer_id = '$cusid'");
    $count_customer_id = $query_customer_id->rowCount();

    if($count_customer_id == 1)
    {

        $generate_customer_id = randomDigits(10);

    }
    else
    {
        $generate_customer_id = $cusid;
    }
    $query = dbQuery("INSERT INTO customers(`customer_id`,`username`,`password`,`email`,`first_name`,`last_name`,`dob`,`id_card`,`family_book_id`,`address`,`district`,`province`,`phone`,`mobile`,`father_name`,`mother_name`,`bank_account_no`,`bank_account_name`) VALUES('$generate_customer_id','$username','$password','$email','$firstname','$lastname','$dob','$idcard','$familybook','$address','$district','$province','$homephone','$mobilephone','$fathername','$mothername','$bankno','$bankname')");

    if($query == true)
    {
        $insert_referrer = dbQuery("INSERT INTO referrers (`parent_id`, `customer_id`, `category_id`, `created`,`modified`) VALUES(NULL, '$generate_customer_id', 2, NOW(), NOW())");
        if($insert_referrer == true)
        {
            echo "OK";
        }
        else
        {
            echo "There is an error please check your information and try again referrers!";
        }
    }
    else
    {
        echo "There is an error please check your information and try again customers!";
    }

但是数据return来自我的AJAX函数,如果return错误我需要多次点击保存客户按钮然后我会return成功然后数据成功保存到数据库。

但是我希望用户只点击一次然后数据就会插入。

如何实现请帮忙!

编辑: 这是 AJAX 函数:

$.ajax({
        type: "POST",
        url: "../ajax/admin/sales/ajaxAddSalesParent.php",
        data: dataString,
        dataType: "html",
        cache: false,
        success: function(responseMessage){
            if(responseMessage == "OK")
            {
                swal({
                      title: "Success",
                      text: "Your requested has been completed!",
                      type: "success",
                      showCancelButton: false,
                      confirmButtonClass: "btn-success",
                      closeOnConfirm: false
                    },
                    function(isConfirm) {
                      if (isConfirm) {
                        window.location.href = "sales_members.php";
                      } 
                });

            }
            else
            {
                $.alert({
                    title: '<h3 style="color: red;">Error!</h3>',
                    content: responseMessage,
                    confirm: function(){

                    }
                });
            }
        }
    });

如果您 运行 在您的数据库中关注 select:

select floor(1000000000 + rand() * 8999999999) as rndID, 
(select customer_id from customers where customer_id=rndID) as uniq;

然后您将收到一个 10 位随机数,希望 uniq 为 NULL。

所以实际上只需在 while 循环中执行此查询,直到字段 uniq 为 NULL 并且您在 rndID 字段中有您的唯一随机数。

我没有你的测试环境,但我认为以下解决方案应该有效:

// get random customer id
$generate_customer_id = 0;
do {
    if ($result = dbQuery("select floor(1000000000 + rand() * 8999999999) as rndID, (select customer_id from customers where customer_id=rndID) as uniq")) {
        if ($row = mysql_fetch_assoc($result)) {
            if ($row['uniq']!=$row['rndID'])
                $generate_customer_id = $row['rndID']; 
        }
    }
} while($generate_customer_id == 0);

$query = dbQuery("INSERT INTO customers(`customer_id`,`username`,`password`,`email`,`first_name`,`last_name`,`dob`,`id_card`,`family_book_id`,`address`,`district`,`province`,`phone`,`mobile`,`father_name`,`mother_name`,`bank_account_no`,`bank_account_name`) VALUES('$generate_customer_id','$username','$password','$email','$firstname','$lastname','$dob','$idcard','$familybook','$address','$district','$province','$homephone','$mobilephone','$fathername','$mothername','$bankno','$bankname')");

if($query == true)
{
    $insert_referrer = dbQuery("INSERT INTO referrers (`parent_id`, `customer_id`, `category_id`, `created`,`modified`) VALUES(NULL, '$generate_customer_id', 2, NOW(), NOW())");
    echo ($insert_referrer) ? "OK" : "There is an error please check your information and try again referrers!";
}
else
{
    echo "There is an error please check your information and try again customers!";
}