1
因此,我正在使用数据库来存储船舶数据。通过数组循环的问题
当我将数据加载到数据库中时,我正在检查船是否已经存在。有时,不止一艘船具有相同的名称。这段代码试图通过这个数组,然后提出所有具有相同名称的船只,然后询问是否合适 - 如果没有,那么它又是一个具有相同名称的船只。
$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)'来查看数组中的内容? –
如果您尝试删除中断,会发生什么情况?当你的'yesno'变量传递给你的条件后,break语句显然会停止循环语句,我似乎无法理解你的条件在做什么。 – Cedric
实际情况似乎已经发生了变化 - 出于某种原因,只有*一个*名称相同的船只会返回。我需要调查此问题。 –