exec("DROP FUNCTION IF EXISTS current_outlet_id"); $db->exec("CREATE FUNCTION current_outlet_id() RETURNS INT DETERMINISTIC RETURN @session_outlet_id"); foreach ($tables as $t) { // Ensure table exists and isn't already a view $stmt = $db->query("SHOW FULL TABLES LIKE '$t'"); $row = $stmt->fetch(PDO::FETCH_NUM); if (!$row) continue; if ($row[1] === 'VIEW') continue; // Already processed // Make sure it has outlet_id $hasCol = false; $cols = $db->query("SHOW COLUMNS FROM `$t`")->fetchAll(PDO::FETCH_ASSOC); foreach ($cols as $c) { if ($c['Field'] === 'outlet_id') $hasCol = true; } if (!$hasCol) { $db->exec("ALTER TABLE `$t` ADD COLUMN IF NOT EXISTS `outlet_id` int(11) DEFAULT 1 AFTER `id`"); } // Alter default to 1 if it's NULL $db->exec("ALTER TABLE `$t` MODIFY `outlet_id` int(11) DEFAULT 1"); // Rename table to _table $db->exec("RENAME TABLE `$t` TO `_$t`"); // Create view $db->exec("CREATE VIEW `$t` AS SELECT * FROM `_$t` WHERE outlet_id = current_outlet_id() OR current_outlet_id() IS NULL OR current_outlet_id() = 0"); // Create trigger $db->exec("CREATE TRIGGER `trg_ins_$t` BEFORE INSERT ON `_$t` FOR EACH ROW BEGIN IF current_outlet_id() IS NOT NULL AND current_outlet_id() != 0 THEN SET NEW.outlet_id = current_outlet_id(); END IF; END"); echo "Processed $t\n"; } } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; }