Example #1
0
 /**
  * Create a new record in database
  * @param  array|object $attributes  Key-value array or object with records's attributes
  * @param  string $table       Table's name
  * @param  string|null $schema *[Optional]* Table's schema, default is null for no schema
  * @param  integer $return     Return method type
  * - if **`RETURN_ID`** will return the id of last inserted record
  * - if **`RETURN_RECORDS`** will return the inserted record
  * - if **`RETURN_NUMBER_OF_RECORDS`** will return the number of records affected
  * @return integer|array
  * @throws ServerException
  * @todo Check RETURNING id for another primary key attribute
  */
 public static function create($attributes, $table, $schema = null, $return = self::RETURN_ID)
 {
     if (is_object($attributes)) {
         $attributes = (array) $attributes;
     }
     $driver = Database::getAdapterName();
     //prepare query
     $query_keys = implode('" , "', array_keys($attributes));
     $query_parameter_string = trim(str_repeat('?,', count($attributes)), ',');
     $query_values = array_values($attributes);
     if ($driver == 'postgresql') {
         //Make sure boolean are strings
         foreach ($query_values as &$queryValue) {
             if (is_bool($queryValue)) {
                 $queryValue = $queryValue ? 'true' : 'false';
             }
         }
     }
     $query = 'INSERT INTO ';
     if ($schema !== null) {
         $query .= sprintf('"%s"."%s"', $schema, $table);
     } else {
         $query .= sprintf('"%s"', $table);
     }
     $query .= sprintf(' ("%s") VALUES (%s)', $query_keys, $query_parameter_string);
     if ($return == self::RETURN_ID) {
         //Return inserted id
         if ($driver == 'postgresql') {
             $query .= ' RETURNING id';
             $id = Database::executeAndFetch($query, $query_values);
             return $id['id'];
         }
         return Database::executeLastInsertId($query, $query_values);
     } elseif ($return == self::RETURN_RECORDS) {
         //Return records
         if ($driver != 'postgresql') {
             throw new ServerExcetion('RETURN_RECORDS works only with postgresql adapter');
         }
         $query .= 'RETURNING *';
         return Database::executeAndFetch($query, $query_values);
     } else {
         //Return number of records affected
         return Database::execute($query, $query_values);
     }
 }