0

This question might probably have been asked somewhere but I just can't seem to find it after much searching.

I have a basic question on how I can prevent the last SQL statement in my code below from executing if it caused any row/data in the table to change.

$query = 'SELECT pdt_code FROM `Products`';
$stmt = $con->query($query);
while ($obj = $stmt->fetch()) {
    $pdt_code[] = $obj['pdt_code'];
}

$args = implode(',', 
            array_map(function($el) { 
                return '('.implode(',', $el).')'; 
            },
            array_chunk(array_fill(0, count($pdt_code), '?'), count($pdt_code))
            )
        );

$query = 'ALTER TABLE `MapProduct` CHANGE product_code product_code SET '.$args.' COLLATE utf8mb4_unicode_ci NOT NULL';
$stmt = $con->prepare($query);
$stmt->execute($pdt_code); // how do I prevent this line from executing if it causes the data in table `MapProduct` to change?

I am trying to execute this from PHP where I query another table for updates to product codes and update the SET() accordingly. However, I had a horrific experience of losing all my data because the update was not properly executed and all the data in product_code got wiped.

3
  • 2
    WHY do you need to automate ALTER TABLE? Commented May 23, 2016 at 13:43
  • @davidstrachan Because the table where products are stored will be modified from time to time. And if the SET fails to be updated accordingly, any new inserts will be rejected. Commented May 23, 2016 at 13:50
  • 2
    You should not use set in this case. Use a lookup table and a foreign key to restrict the list product codes. In that case all you need to do is to insert a new record into your product codes lookup table. Commented May 23, 2016 at 15:03

1 Answer 1

1

Although mysql's SET data type can be used to restrict list of values being entered. However, it is not flexible and requires an alter table to update the list of values. If you frequently have to do this - and if you build a functionality to do that, then you need to do this frequently - then the SET data type is simply not for you.

I would create a separate table for product types and I would simply reference this table with a foreign key from your mapproduct table. This way adding a new product type to the allowed list inly requires an insert statement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.