2015-12-15 94 views
3

我正在研究板塊分佈系統。我爲變量$quantity分配了一個值,它會說明要分配多少個板塊。如果記錄已經存在,如何跳過迭代? - PHP

$plate_prefix and $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; 
       } 
      } 
+0

做出一個選擇查詢,其中'yourfield' =「$ yourplate 」。然後在插入之前做一個'if else'語句... –

+1

如果數據庫設計得很好('plate_prefix'和'plate_suffix'上的'UNIQUE'限制),INSERT'會產生一個錯誤,從而阻止重複的板塊。請注意,您的代碼容易受到SQL注入攻擊:使用[PDO](http://stackoverflow.com/a/6981200/1980659)。 – ForguesR

回答

1

考慮使用continue命令有條件地跳過下一次迭代。我還修改代碼以使用mysqli數據庫API爲mysql*被棄用(即使是在PHP 7停產 - 應你的虛擬主機提供商的更新,你將面臨的問題):

# 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(); 
+0

非常感謝。我會考慮這個。 – gauche23

相關問題