【问题标题】:How to skip an iteration if record already exists? - PHP如果记录已经存在,如何跳过迭代? - PHP
【发布时间】:2015-12-15 02:06:41
【问题描述】:

我正在开发一个印版分配系统。我为变量$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;
                }
            }

【问题讨论】:

  • 进行选择查询,其中yourfield = '$yourplate'。然后在插入之前执行if else 语句...
  • 如果数据库设计良好(UNIQUE 约束plate_prefixplate_suffixINSERT 无论如何都会引发错误,从而防止重复板。请注意,您的代码易受 SQL 注入攻击:使用 PDO

标签: php sql


【解决方案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();

【讨论】:

  • 非常感谢。我会考虑的。
猜你喜欢
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2019-11-18
  • 1970-01-01
  • 2016-08-07
  • 2021-09-10
  • 1970-01-01
相关资源
最近更新 更多