duandeng2011 2017-09-05 02:19
浏览 100

循环遍历数组的问题

So, I'm using a database to store ship data.

As I load data into the database, I am checking whether the ship already exists. Sometimes, more than one ship has the same name. This code tries to go through the array, pull out all the ships with the same name, and then ask, in turn if that is the right one- if not, then it's yet another with the same name.

 $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"]  . "
";
             $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);
      }
  }

So the problem is, I know that I have at least three ships with the same name in the first set of data (that are different). The problem is, it only ever asks about the first one. When I put 'n', it just goes on, and never asks about the second ship with the same name that already exists.

I think it's a problem with the Foreach loop and the break statement. I'd appreciate any help with this

  • 写回答

1条回答 默认 最新

  • dos71253 2017-09-05 03:05
    关注

    I've figured out the problem.

    Because of the loop- I wasn't resetting the "Ship_Id" variable, which meant that the second or nth time a ship with the same name came around, a new ship wasn't created.

    Now I've solved that. So the problem isn't this code at all- it's other code.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用