title: Insert from source database into destination database, different servers
body: <p>I have 2 database servers, a source and destination.</p>
  
  <p>I've recently cloned 2 tables from the source to the destination and I have a script that is using the max id of destination table to insert everything after it from the source. This is run every 5 minutes as a rough approach to update the data on the destination server.</p>
  
  <p>It's missing records though so I'm hoping for a different approach.</p>
  
  <p>I want to select all from the source table, and if the id doesn't exist in the destination then insert it. I have no idea the best way to do this but I need something accurate so that it won't miss records anymore.</p>
  
  <p>Here's the current script:</p>
  
  <pre><code>$latest_result_summary = $conn2-&gt;query("
          SELECT MAX(`NOTABLECALLID`) FROM `ambition`.`callsummary`");
  $latest_row_summary = $latest_result_summary-&gt;fetch_row();
  $latest_summary_id = $latest_row_summary[0];
  
  //select All rows from the source phone database(callsummary)
  $source_data_summary = mysqli_query($conn, "
          SELECT * FROM `cdrdb`.`callsummary` 
          WHERE `NOTABLECALLID` &gt; $latest_summary_id");
  
  // Loop on the results
  while($source_summary = $source_data_summary-&gt;fetch_assoc()) {
  
          // Check if row exists in destination phone database, cdrdb.callsummary
          $row_exists_summary = $conn2-&gt;query("
                  SELECT NOTABLECALLID FROM ambition.callsummary 
                  WHERE NOTABLECALLID = '".$source_summary['NOTABLECALLID']."' ")
          or die(mysqli_error($conn2));
  
          //if query returns false, rows don't exist with that new ID.
          if ($row_exists_summary-&gt;num_rows == 0){
  
                  //Insert new rows into ambition.callsummary
                  $stmt_summary = $conn2-&gt;prepare("
                          INSERT INTO ambition.callsummary 
                          (NOTABLECALLID, STARTTIME, ENDTIME, DURATION, 
                           ANSWERED, ts, firstcallid)
                          VALUES ( ?, ?, ?, ?, ?, ?, ?)")
                  or die(mysqli_error($conn2)) ;
  
                  mysqli_stmt_bind_param($stmt_summary, "issiisi", 
                          $source_summary['NOTABLECALLID'], 
                          $source_summary['STARTTIME'],
                          $source_summary['ENDTIME'], 
                          $source_summary['DURATION'],
                          $source_summary['ANSWERED'], 
                          $source_summary['ts'],
                          $source_summary['firstcallid'] 
                  );
  
                  $stmt_summary-&gt;execute() or die(mysqli_error($conn2));
  
  
          }
  }       
  </code></pre>
  
  <p>The key here is we're not setup with our dba and phone system to preform replication, so I just need a good accurate way to insert to destination if it doesn't exist.</p>