updateHandler.php (1622B)
1 <?php 2 class UpdateHandlerFactory { 3 public function createHandler($tableName, $condition) { 4 switch ($tableName) { 5 default: 6 return new GenericUpdateHandler($tableName, $condition); 7 } 8 } 9 } 10 11 class GenericUpdateHandler implements PostHandler { 12 private $tableName; 13 private $pdo; 14 private $condition; 15 16 public function __construct($tableName, $condition) { 17 $this->condition = $condition; 18 $this->tableName = $tableName; 19 $db = dbconnection::getInstance(); 20 $this->pdo = $db->getPdo(); 21 } 22 23 public function handlePostData($data) { 24 if (!isUpdate($data)) return; 25 26 logg("Updating records in: " . $this->tableName); 27 28 unset($data['tableName']); 29 unset($data['operationType']); 30 31 $setClause = []; 32 foreach ($data as $column => $value) { 33 $setClause[] = "$column = '{$value}'"; 34 } 35 $setClause = implode(', ', $setClause); 36 37 $sql = "UPDATE {$this->tableName} SET {$setClause} WHERE {$this->condition}"; 38 $stmt = $this->pdo->prepare($sql); 39 40 if (!$stmt->execute()) { 41 throw new Exception("Failed to update data in {$this->tableName}."); 42 } 43 44 RefreshTables(); 45 } 46 47 public function getOperationType() { 48 return "UPDATE"; 49 } 50 } 51 52 function isUpdate($postData) { 53 return $postData["operationType"] === "UPDATE" ? true : false; 54 } 55 ?>