我正在研究印版分配系统。我为变量 $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;
}
}
最佳答案
考虑使用 continue命令有条件地跳到下一次迭代。我还修改了代码以使用 mysqli作为 mysql*
的数据库 API 已弃用(甚至在 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();
关于php - 如果记录已经存在,如何跳过迭代? - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279913/