如果记录已经存在,如何跳过迭代? - PHP

时间:2015-12-15 02:06:41

标签: php sql

我正在研究一种板式分配系统。我为变量$quantity分配了一个值,它会说明要分配多少个印版。

$plate_prefix$plate_suffix是要分配的印版数量的起点。 但有一个例子是,有一个定制的板块将在板数之间。

示例:我需要30个盘子,AAA-1001是开始,但AAA-1020已经开始使用,所以我需要跳过AAA-1020才能将AAA-1001牌照变成AAA-1032。

    $region = $_POST['region'];
    $district_office = $_POST['district_office'];
    $quantity = $_POST['quantity'];
    $plate_prefix = $_POST['plate_prefix'];
    $plate_suffix = $_POST['plate_suffix'];

        $loop = 0;
        while($loop < $quantity)
        {
            if($plate_suffix <= 9999)
            {
                $sql1 = mysql_query("INSERT INTO mv_plate (`plate_prefix`, `plate_suffix`, `region`, `district_office`, `status`) 
                VALUES ('$plate_prefix', '$plate_suffix', '$region', '$district_office', 'Available')");

                $plate_suffix = $plate_suffix+1;
                $loop = $loop+1;
            }
                else
                {
                    $plate_prefix = ++$plate_prefix;
                    $plate_suffix = 1001;
                }
            }

1 个答案:

答案 0 :(得分:1)

考虑使用continue命令有条件地跳到下一次迭代。我还修改了代码以使用mysqli数据库API,因为mysql*已弃用(甚至在PHP 7中已停止 - 如果您的webhost更新,您将面临问题):

# DATABASE CONNECTION
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$loop = 0;
while($loop < $quantity) {  

    # SKIP TO NEXT ITERATION FOR PLATE ALREADY TAKEN  
    if($plate_suffix == 1020) { 
       $plate_suffix++;
       $loop++;
       continue; 
    }

    if($plate_suffix <= 9999) {          
       # PREPARING APPEND QUERY STATEMENT  
       $stmt = $conn->prepare("INSERT INTO mv_plate (`plate_prefix`, `plate_suffix`,
                                                   `region`, `district_office`, `status`) 
                               VALUES (?, ?, ?, ?, 'Available')");

       # BINDING PARAMETERS
       $stmt->bind_param("siss", $plate_prefix, $plate_suffix, $region, $district_office);
       # EXECUTING QUERY
       $stmt->execute();    

       $plate_suffix++;
       $loop++;
   }
   else {
        $plate_prefix = ++$plate_prefix;
        $plate_suffix = 1001;
   }                       
}

# CLOSE STATEMENT AND CONNECTION
$stmt->close();
$conn->close();