title: Import big CSV file to dependent MySQL tables using PHP with duplicate checking
body: <p>I'm reading about 50,000+ .csv rows and create insert query. There is one dynamic value in insert query values. It's from SELECT if exists or INSERT if doesn't and get the inserted id. This is just testing purpose, just ignore the security lack.</p>
  
  <pre><code>$multiquery = "";
  $lines = file($furl);
  
  foreach ($lines as $line_num =&gt; $line) {
      if (($line_num + 1) % 1000 == 0) {
          include('connection.php');
      }
  
      $cols = split(';', $line);
  
      $originid = 1;
      $dest = $cols[3];
      $cost = (int)$cols[5];
  
      // === start: consume a lot of connections ===
      $query = "SELECT id FROM dests WHERE name = '$dest'";
      if (!$dests = mysqli_query($link, $query)) {
          die(json_encode(array("errmsg" =&gt; "Selecting existing shipdest. Error: ".mysqli_error($link))));
      }
      if (mysqli_num_rows($dests) &gt; 0) {
          $dest = mysqli_fetch_assoc($dests);
      }
      else {
          $query = "INSERT INTO dests (name) VALUES ('$dest')";
          if (!mysqli_query($link, $query)) {
              die(json_encode(array("errmsg" =&gt; "Inserting new dest.")));
          }
  
          $dest['id'] = mysqli_insert_id($link);
      }
      // === end: consume a lot of connections ===
  
      $multiquery .= "INSERT INTO packages (id_origin, id_dest, cost) VALUES ($originid, ".$dest['id'].", ".$cost."); ";
  
      if (($line_num + 1) % 1000 == 0 &amp;&amp; !mysqli_multi_query($link, $multiquery)) {
          die(json_encode(array("errmsg" =&gt; "Failed at line ".$line_num)));
      }
  }
  </code></pre>
  
  <p>How to merge that PHP block as id_dest value in $multiquery?</p>