Example #1
0
 /**
  * Execute a complex manipulation on the database.
  * A manipulation is an array of insert / or update sequences.  The keys of the array are table names,
  * and the values are map containing 'command' and 'fields'.  Command should be 'insert' or 'update',
  * and fields should be a map of field names to field values, including quotes.  The field value can
  * also be a SQL function or similar.
  * @param array $manipulation
  */
 function manipulate($manipulation)
 {
     foreach ($manipulation as $table => $writeInfo) {
         if (isset($writeInfo['fields']) && $writeInfo['fields']) {
             $fieldList = array();
             foreach ($writeInfo['fields'] as $fieldName => $fieldVal) {
                 $fieldList[] = "`{$fieldName}` = {$fieldVal}";
             }
             $fieldList = implode(", ", $fieldList);
             if (!isset($writeInfo['where']) && isset($writeInfo['id'])) {
                 $writeInfo['where'] = "ID = {$writeInfo['id']}";
             }
             switch ($writeInfo['command']) {
                 case "update":
                     $sql = "update `{$table}` SET {$fieldList} where {$writeInfo['where']}";
                     $this->query($sql);
                     // If numAffectedRecord = 0, then we want to run instert instead
                     if (!$this->affectedRows()) {
                         if (!isset($writeInfo['fields']['ID']) && isset($writeInfo['id'])) {
                             $fieldList .= ", ID = {$writeInfo['id']}";
                         }
                         $sql = "insert into `{$table}` SET {$fieldList}";
                         $this->query($sql, null);
                     }
                     break;
                 case "insert":
                     if (!isset($writeInfo['fields']['ID']) && isset($writeInfo['id'])) {
                         $fieldList .= ", ID = {$writeInfo['id']}";
                     }
                     $fieldList = Database::replace_with_null($fieldList);
                     $sql = "insert into `{$table}` SET {$fieldList}";
                     $this->query($sql);
                     break;
                 default:
                     $sql = null;
                     user_error("Database::manipulate() Can't recognise command '{$writeInfo['command']}'", E_USER_ERROR);
             }
         }
     }
 }