0

I have a small database with some books and stocks that looks basically like this:

| id |       book             |     stock    |
|  1 | Harry Potter...        |      83      |
|  2 | Lord of the rings...   |      45      |
|  3 | In Search of Lost Time |       8      |

And i'm using this code to insert multiple records at once - i'm taking the records from a CSV file using php - (i found it here on stackoverflow):

$pdo->beginTransaction();
$fields = ['book', 'stock'];
$values = [];

foreach($products as $product){
    $bind[] = '(?,?)';
    $values = array_merge($values, array_values($product));
}

$sql = "INSERT INTO books (" . implode(",", $fields) . ") VALUES " . implode(',', $bind);

$statement = $pdo->prepare ($sql);
try {
    $statement->execute($values);
} catch (PDOException $e){
   echo $e->getMessage();
}
$pdo->commit(); 

Now the problem that i'm having is that all this records are supposed to be unique but when i'm running this code, to check if there is any update in terms of book - or books - stock inside the CSV file, it just ads the same book over and over again (with a different id).

Is there a way to somehow avoid that duplication but in the same time to insert multiple records using PDO and binding values?

Thank you for taking time to read this! :D

emma
  • 761
  • 5
  • 20
  • 2
    *"Is there a way to somehow avoid that duplication but in the same time to insert multiple records using PDO and binding values?"* - [INSERT ... ON DUPLICATE KEY](https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html). – Funk Forty Niner Aug 09 '18 at 15:08
  • 1
    Hey Funk, i only know how to use that for a single record :( and i can't find a way to use `on duplicate` for multiple records, can you help me? X_X – emma Aug 09 '18 at 15:11

0 Answers0