4
In a virtual shop panel I am building the products have relations by color and size, where each product color has a size.
This is a part of my database to better understand the problem: http://sqlfiddle.com/#! 9/d0dee
When the user wants to associate the colors to a product in the panel it is forwarded to a page with all colors (list of checkbox) and this one he selects the colors and sends the form to php processing with the following script:
Obs.: $database
is an instance of Doctrine DBAL
$checking = [];
$colors = (array) $_POST['colors'];
$ids = [];
foreach($colors as $color) if(is_numeric($color)) $ids[]=$color;
$emptyTableQuery = $database->createQueryBuilder();
$emptyTableQuery -> delete('product_colors')
-> where('id_product = :idProduct AND id_color NOT IN (:ids)')
-> setParameters([':idProduct'=>$id,':ids'=>implode(',',$ids)]);
$emptyTable = $emptyTableQuery->execute();
foreach($colors as $color)
$checking[] = $database->insert(
'product_colors',
[
'id_product'=> $id,
'id_color'=> $color
],
['id_product'=>\PDO::PARAM_INT,'id_color'=>\PDO::PARAM_INT]
);
When a new product is inserted the code works perfectly, however, when the colors of the product are updated the colors already in the database are duplicated...
Before the current code ALL colors were removed from the table, or is, she was completely clean, which resulted in me having a problem major: there is a third relation with the table called 'sizes_by_product_color' where the sizes for each are stored color and the respective stocks, ie if I delete everything too this data was lost and the customer would have to register all the sizes for colors, before existing, again...
This is a part of my database to better understand the problem: http://sqlfiddle.com/#! 9/d0dee
How could I solve my problem in a practical way? there is some solution for SQL or I will have to select to check in PHP?
I do not understand why it duplicates, since you are deleting the same data before entering..
– Lucio Rubens
So @lúcio-Rubens, before I deleted all the colors for the product (and consequently its data) and worked, but the problem was that I lost the data that the user wanted to be kept, with the current code, I keep the data that the user did not mess with (with the
id_color NOT IN (:ids)
of line 9), but everything is inserted again, duplicating content. (ex.: color 1 has been selected and it already exists in the table, so it is not excluded in the '$emptyTableQuery', but it is rewritten in theinsert
of line 15...– MateusDemboski