创建唯一订单号时出现增量问题

时间:2018-08-10 19:38:35

标签: php jquery

我正在创建这样的订单号:

    ACC4_11082018_1    

    ACC4_11082018_2

    ACC4_11082018_3

    ACC4_11082018_4

    ACC4_11082018_5
    .
    .
    .
    .
    etc.

我在增加最后一位数字时遇到问题。 我尝试了代码

date_default_timezone_set('Asia/Kolkata');
$myDate = date('dmY');
$get_id=4;
$i=1;
echo $order_no='ACC'.$get_id.'_'.$myDate.'_'.$i;
$i++;

您能帮我吗?

2 个答案:

答案 0 :(得分:0)

我不知道您将在哪里使用此代码/逻辑,但这会给您带来无限的可能性:

date_default_timezone_set('Asia/Kolkata');

$myDate = date('dmY');
$get_id=4;

$i=0;

while( ++$i )
{
    echo $order_no='ACC'.$get_id.'_'.$myDate.'_'.$i;

    // echo '<br>'; // uncomment this if you want it to look normal in your browser
}

或者如果不需要无限,那么:

date_default_timezone_set('Asia/Kolkata');

$myDate = date('dmY');
$get_id=4;

$i=0;

// stop after 1,000
while( ++$i <= 1000 )
{
    echo $order_no='ACC'.$get_id.'_'.$myDate.'_'.$i;

    // echo '<br>'; // uncomment this if you want it to look normal in your browser
}

答案 1 :(得分:0)

如果您真的想为任何商品生成唯一的订单号: 您必须检查数据库或注释中是否已存在该订单号

/* --------------------------- New order number --------------------------- */

    $check_for_order = $con->query("SELECT `order_no` FROM `table` ORDER BY `id` DESC LIMIT 1");
    if($check_for_order->num_rows==1){

    $row=mysqli_fetch_array($check_for_order);
    $previous_order = trim($row['order_no']);

    $new_order = $previous_order + 1;

    $insert_order_number = $con->query("INSERT INTO `table`(`order_no`) VALUES ('{$new_order}')");

    }else{

    $previous_order = 1;

    $on_date = date("Ymdhis"); // or you can use time() instead

    $new_order = $on_date.$previous_order;

    $insert_order_number = $con->query("INSERT INTO `table`(`order_no`) VALUES ('{$new_order}')");
    }

    /* ----------------------- New Order Number here -------------------------- */

    $order_no = $new_order;