【发布时间】:2018-02-13 05:27:05
【问题描述】:
所以,我正在使用数据库来存储船舶数据。
当我将数据加载到数据库中时,我正在检查这艘船是否已经存在。有时,不止一艘船有相同的名称。这段代码试图遍历数组,取出所有同名的飞船,然后依次询问这是否是正确的——如果不是,那么它是另一个同名的飞船。
$sql = "SELECT Ship_Primary_Key, ship_original_rate, Ship_Launch_Year from Ships WHERE Ship_Name = '" . $shipname . "'";
$result = $conn->query ($sql);
if ($result-> num_rows > 0) //Does the ship name already exist in the DB? {
$ships_in_db = mysqli_fetch_all ($result,MYSQLI_ASSOC);
foreach ($ships_in_db as $row) {
echo "new record is " . $shipname . " as a " . $shiprate . ". Records already include " . $shipname . ", launched " . $row["Ship_Launch_Year"] . " as a " . $row ['ship_original_ra
$yesno = trim(fread(STDIN,5));
if ($yesno == "y" || $yesno == "yes") {
//ship already exists in the DB. Get the Key
echo $shipname . " is not new to the database and the key is " . $row["Ship_Primary_Key"] . "\n";
$shipkey = $row["Ship_Primary_Key"];
break 1;
}
}
//if you get through the loop of ships without assigning a primary key, ship is new
if (empty($shipkey)) {
$shipkey = write_ship_to_DB($shipname,$shiprate,$launchyear,$launchname,$conn);
}
}
所以问题是,我知道在第一组数据中我至少有 三艘 船具有相同的名称(它们不同)。问题是,它只询问第一个。当我输入“n”时,它会继续,并且从不询问已经存在的具有相同名称的第二艘船。
我认为这是 Foreach 循环和 break 语句的问题。 我会很感激这方面的任何帮助
【问题讨论】:
-
您是否尝试通过
var_dump($ships_in_db)来查看数组中的内容? -
如果您尝试删除中断会发生什么? break 显然会在循环语句在您的
yesno变量上传递您的条件后停止循环语句,我似乎无法理解您的条件在做什么。 -
有些东西似乎实际上发生了变化——出于某种原因,只返回了 一个 同名的船。我需要对此进行调查。
-
我已将代码简化为simpler form。它按预期工作。您能否在您的计算机上尝试一下,看看会发生什么?
-
对不起,你的简化代码在哪里?
标签: php sql database loops foreach