Search code examples
phphtmlmysqlsqldelete-row

DELETE rows that are not in INSERT statement mysql


I have following situation:

I have a mysql table in which I upload my inventory. The table's structure is like:

<pre>
    <table>
        <thead>
            <tr>
                <th>SKU</th>
                <th>price</th>
                <th>quantity</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>393939</td>
                <td>39.99</td>
                <td>32</td>
            </tr>
        </tbody>
    </table>
</pre>

Actually I do it as follows:

mysqli_query(
    $sql, 
    "INSERT IGNORE INTO de_minmaxpreis(sku, price, quantity) VALUES ('$teile[3]', '$teile[4]', '$teile[5]')"
);

Now, if I have data taken out of the inventoryfile I use to import, I want that the data which isn't in the inventoryfile be deleted from the table. I can't truncate the table prior to import the new file, because pricing details might have changed and the priority to this is in my mySql table. (More up to date).

Hm, hope someone understands my question and can help.


Solution

  • If I got you right , you need to insert just new SKUs and delete ones that are not present in new import. Meaning you do not need to update anything from new import like "quantity" If so you can do, and assuming that sku is unique.

    $sql="select sku from de_minmaxpreis";
    //get the skus in array like $oldskus[]='somesku';
    
    //make a new data array look like $newDataSkus[$sku]=$dataArray;
    foreach($oldskus as $oldSku){
      //here if odlsku is not present in new data delete it from a DB
      if( ! array_key_exists($oldSku , $newDataSkus ){
         //old sku not present anymore delete it
         $sql="delete from de_minmaxpreis .... "
      }else{
        //as sku is in DB remove that sku from newData at the end you will get data that is new and needs to be inserted
          unset($newDataSkus[$oldSku];
      } 
    
    }
    //finally inset new data
    foreach($newDataSkus as $tiele){
    mysqli_query(
        $dbCon, 
        "INSERT INTO de_minmaxpreis(sku, price, quantity) VALUES ('$teile[3]', '$teile[4]', '$teile[5]')"
    );
    }