public static function insert($table, array $params = array()) { $attributes = $params; $instance = new self(); $sql = "INSERT INTO " . $table . " ("; $sql .= join(", ", array_keys($attributes)); $sql .= ")VALUES("; $sql .= ":"; $sql .= join(", :", array_keys($attributes)); $sql .= ")"; try { $prep = $instance->prepare($sql); foreach ($attributes as $key => $value) { $prep->bindValue(':' . $key, $value); } if ($prep->execute()) { $instance->id = $instance->lastInsertId(); return true; } else { throw new \Exception("data could not be saved"); //return false; } } catch (\PDOException $e) { echo $e->getMessage(); } catch (\Exception $e) { echo $e->getMessage(); } }
public function create() { $instance = new self(); $attributes = $this->attributes(); unset($attributes['id']); foreach ($attributes as $key => $value) { if ($value == null) { unset($attributes[$key]); } } $sql = "INSERT INTO " . static::$table . " ("; $sql .= join(", ", array_keys($attributes)); $sql .= ")VALUES("; $sql .= ":"; $sql .= join(", :", array_keys($attributes)); $sql .= ")"; try { $prep = $instance->prepare($sql); foreach ($attributes as $key => $value) { $prep->bindValue(':' . $key, $value); } if ($prep->execute()) { $this->id = $instance->lastInsertId(); return true; } else { throw new \Exception("data could not be saved"); //return false; } } catch (\PDOException $e) { echo $e->getMessage(); } catch (\Exception $e) { echo $e->getMessage(); } }