title: INSERT where doesn't exist in php script, comparing 2 tables
body: <p>I currently have a script that runs every 5 minutes and selects the data from a table on server 1 and an  identical table on server2. This is a workaround for replication, essentially, since we don't have that option currently.</p>
  
  <p>The script is successful but I've realized that it misses records sometimes, for whatever reason. The current script selects all records from the destination table, stores the max primary key, selects all data from the source table and then inserts anything with a greater Primary key into the dest. table.</p>
  
  <p>I'd like to modify the script slightly and instead of using max id, just say "if a row has an primary key that doesn't exist in the destination table, insert that row there."</p>
  
  <p>Again these are cloned tables so the structure is the same and they both use AI Primary Keys.</p>
  
  <p>Here's the current working script:</p>
  
  <pre><code>$latest_result = $conn2-&gt;query("SELECT MAX(`SESSIONID`) FROM 
  `ambition`.`session`");
  $latest_row = $latest_result-&gt;fetch_row();
  $latest_session_id = $latest_row[0];
  
   //Select All rows from the source phone database
   $source_data = mysqli_query($conn, "SELECT * FROM 
   `cdrdb`.`session` WHERE `SESSIONID` &gt; $latest_session_id");
  
   // Loop on the results
   while($source = $source_data-&gt;fetch_assoc()) {
  
   // Check if row exists in destination phone database
   $row_exists = $conn2-&gt;query("SELECT SESSIONID FROM 
   ambition.session WHERE SESSIONID = '".$source['SESSIONID']."' ") or 
   die(mysqli_error($conn2));
  
   //if query returns false, rows don't exist with that new ID.
   if ($row_exists-&gt;num_rows == 0){
  
   //Insert new rows into ambition.session
   $stmt = $conn2-&gt;prepare("INSERT INTO ambition.session (SESSIONID, 
   SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
   DIALPLANNAME,TERMINATIONREASONCODE  //etc. There are a lot of columns so I 
   ommitted the others
  </code></pre>
  
  <p>Is there a way I can slightly modify this to just insert what doesn't exist rather than relying on the MAX ID?</p>
  
  <p>Or is there something here that would be a culprit as to why it's missing records?</p>