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