protected function setUp() { $this->PDO = DB::getInstance(); $this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->PDO->exec('INSERT INTO `' . PREFIX . 'equipment_type` (`name`, `accountid`) VALUES ("Test", 1)'); $this->Typeid = $this->PDO->lastInsertId(); }
public function insert(Diario $diario) { $stm = $this->pdo->prepare('INSERT INTO obras_diario( cliente_id, cod_obra, titulo, arquivo_lnk, reg_status, ult_atualizacao ) VALUES ( :cliente_id, :cod_obra, :titulo, :arquivo_lnk, :reg_status, :ult_atualizacao )'); $stm->bindValue(':cliente_id', $diario->getClienteId(), PDO::PARAM_INT); $stm->bindValue(':cod_obra', $diario->getCodObra(), PDO::PARAM_INT); $stm->bindValue(':titulo', $diario->getTitulo(), PDO::PARAM_STR); $stm->bindValue(':arquivo_lnk', $diario->getArquivoLnk(), PDO::PARAM_STR); $stm->bindValue(':reg_status', $diario->getRegStatus(), PDO::PARAM_STR); $stm->bindValue(':ult_atualizacao', $diario->getUltAtualizacao(), PDO::PARAM_STR); if ($stm->execute()) { return (int) $this->pdo->lastInsertId(); } throw new \RuntimeException('Falha ao inserir'); }
public function __construct() { parent::__construct(); $pdo = new PDO('sqlite::memory:'); $artists = [['name' => 'The Smashing Pumpkins', 'albums' => [['name' => 'Siamese Dream', 'year' => 1993, 'songs' => ['Hummer', 'Disarm', 'Soma', 'Mayonaise']], ['name' => 'Pisces Iscariot', 'year' => 1994, 'songs' => ['Plume', 'Whir', 'Landslide']]]], ['name' => 'Placebo', 'albums' => [['name' => 'Without You I\'m Nothing', 'year' => 1998, 'songs' => ['Pure Morning', 'Brick Shithouse', 'You Don\'t Care About Us', 'Allergic (to Thoughts of Mother Earth)', 'Every You Every Me']], ['name' => 'Black Market Music', 'year' => 2000, 'songs' => ['Taste in Men', 'Special K', 'Spice & Malice', 'Black-Eyed', 'Peeping Tom']], ['name' => 'Sleeping With Ghosts', 'year' => 2002, 'songs' => ['English Summer Rain', 'This Picture', 'Special Needs', 'Second Sight', 'Centrefolds']]]], ['name' => 'The Who', 'albums' => [['name' => 'Who\'s Next', 'year' => 1971, 'songs' => ['Baba O\'Riley', 'My Wife', 'Going Mobile', 'Behind Blue Eyes']]]]]; $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE artists (id INTEGER PRIMARY KEY, name TEXT)"); $pdo->exec("CREATE TABLE albums (id INTEGER PRIMARY KEY, name TEXT, year INTEGER, artist_id INTEGER)"); $pdo->exec("CREATE TABLE songs (id INTEGER PRIMARY KEY, name TEXT, track_number INTEGER, album_id INTEGER)"); $insert_artist = $pdo->prepare("INSERT INTO artists (name) VALUES (?)"); $insert_album = $pdo->prepare("INSERT INTO albums (name, year, artist_id) VALUES (?, ?, ?)"); $insert_song = $pdo->prepare("INSERT INTO songs (name, track_number, album_id) VALUES (?, ?, ?)"); $pdo->beginTransaction(); foreach ($artists as $artist) { $insert_artist->execute([$artist['name']]); $artist_id = $pdo->lastInsertId(); foreach ($artist['albums'] as $album) { $insert_album->execute([$album['name'], $album['year'], $artist_id]); $album_id = $pdo->lastInsertId(); foreach ($album['songs'] as $track_number => $song) { $insert_song->execute([$song, $track_number + 1, $album_id]); } } } $this->pdo = $pdo; }
public function save(\Riimu\BareMVC\Model\Model $model) { if (!$model instanceof $this->modelName) { throw new \RuntimeException('Unexpected model "' . get_class($model) . '". ' . 'Was expecting instance of "' . $this->modelName . '"'); } if ($model->isNew()) { $data = $model->getDatabaseValues(); $primary = $model->getPrimaryKeys(); if (count($primary) === 1 && $model->get($primary[0]) === null) { unset($data[$primary[0]]); $updatePrimaryKey = true; } else { $updatePrimaryKey = false; } $this->insert($data); if ($updatePrimaryKey) { $model->set($primary[0], $this->db->lastInsertId()); } $model->setNewStatus(false); } else { $data = $model->getDatabaseValues(); foreach ($model->getPrimaryKeys() as $key) { $where[$key] = ['=', $data[$key]]; unset($data[$key]); } $this->update($data, $where); } }
/** * Gets the id of the last inserted row. * * @return mixed Row id */ public function insert_id() { if ($this->db_type == 'pgsql') { return $this->execute('SELECT lastval() as id')->current()->id; } return $this->conn->lastInsertId(); }
/** * Creates or updates a user in a data source. * * @param Models\User &$user * @return bool */ public function save(Models\User &$user) { //Convert the user model but don't convert the githubRepos field on the model. $modelArray = $this->converter->modelToEntityArray($user, ['githubRepos']); //Prevent someone from setting a different ID for a preexisting entry. if (isset($modelArray['id'])) { unset($modelArray['id']); } //Set the updated_at value in the database $modelArray['updated_at'] = date('Y-m-d G:i:s'); $keys = array_keys($modelArray); $vals = array_values($modelArray); if (isset($user->id)) { $query = $this->pdo->prepare('UPDATE users SET ' . implode('=?, ', $keys) . '=? WHERE id=? LIMIT 1'); $vals[] = $user->id; return $query->execute($vals); } else { $query = $this->pdo->prepare('INSERT INTO users (' . implode(',', $keys) . ') VALUES (' . implode(',', array_fill(0, count($vals), '?')) . ')'); if ($query->execute($vals)) { //Refetch to populate everything properly. $user->id = $this->pdo->lastInsertId(); return true; } } return false; }
protected function setUp() { $this->PDO = DB::getInstance(); $this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->PDO->exec('INSERT INTO `runalyze_training` (`accountid`) VALUES (0)'); $this->ActivityID = $this->PDO->lastInsertId(); }
/** * Duplicates the provided category into the provided parent category * * @param int $originalCategoryId * @param int $parentId * @param bool $copyArticleAssociations * @return int * @throws \RuntimeException */ public function duplicateCategory($originalCategoryId, $parentId, $copyArticleAssociations) { $originalCategoryStmt = $this->connection->prepare('SELECT * FROM s_categories WHERE id = :id'); $originalCategoryStmt->execute([':id' => $originalCategoryId]); $originalCategory = $originalCategoryStmt->fetch(\PDO::FETCH_ASSOC); if (empty($originalCategory)) { throw new \RuntimeException('Category ' . $originalCategoryId . ' not found'); } $newPosStmt = $this->connection->prepare('SELECT MAX(`position`) FROM s_categories WHERE parent = :parent'); $newPosStmt->execute([':parent' => $parentId]); $newPos = (int) $newPosStmt->fetchColumn(0); $originalCategory['position'] = $newPos + 1; $originalCategory['parent'] = $parentId; unset($originalCategory['id']); unset($originalCategory['path']); $valuePlaceholders = array_fill(0, count($originalCategory), '?'); $insertStmt = $this->connection->prepare("INSERT INTO s_categories (`" . implode(array_keys($originalCategory), "`, `") . "`)\n VALUES (" . implode($valuePlaceholders, ", ") . ")"); $insertStmt->execute(array_values($originalCategory)); $newCategoryId = $this->connection->lastInsertId(); $this->rebuildPath($newCategoryId); $this->duplicateCategoryAttributes($originalCategoryId, $newCategoryId); $this->duplicateCategoryRestrictions($originalCategoryId, $newCategoryId); if ($copyArticleAssociations) { $this->duplicateCategoryArticleAssociations($originalCategoryId, $newCategoryId); } return $newCategoryId; }
public function insert($table, $dataobj) { if (is_array($dataobj)) { $dataobj = (object) $dataobj; } if (empty($dataobj) || !is_object($dataobj)) { return false; } if (isset($dataobj->id)) { unset($dataobj->id); } $fields = ''; $values = ''; foreach ($dataobj as $field => $value) { if ($fields) { $fields .= ', '; } if ($values) { $values .= ', '; } $fields .= "`" . $field . "`"; $values .= "'" . $value . "'"; } $sql = "INSERT INTO {$table} ({$fields}) VALUES({$values})"; $this->_db->query($sql); return $this->_db->lastInsertId(); }
public function lastInsertId() { try { return $this->pdo->lastInsertId(); } catch (\PDOException $ex) { throw new \SNDatabase\ConnectionFailedException($ex->errorInfo[2], $ex->getCode(), $ex); } }
public function logStart(ForgeUpgrade_Bucket $bucket) { $sth = $this->dbh->prepare('INSERT INTO ' . $this->t['bucket'] . ' (script, start_date) VALUES (?, NOW())'); if ($sth) { $sth->execute(array($bucket->getPath())); $bucket->setId($this->dbh->lastInsertId()); } }
/** * Grab last inserted Id * * @param string|null $name * @return int * @throws DatabaseException */ public function lastInsertId(string $name = null) : int { try { return (int) $this->pdo->lastInsertId($name); } catch (\PDOException $e) { throw DatabaseException::pdoError($e->getMessage()); } }
/** * Execute the query and insert the expected entries in the database. * * @throws \Exception When an error is occurred while the insertion. */ public function execute() { $query = $this->factory->builder($this->insert)->process(); $result = $this->pdo->query($query); if (!$result) { throw new \Exception('An error is while the insertion occurred! (query: "' . $query . '")'); } return $this->pdo->lastInsertId(); }
/** * Create a new object and return it * * @param array $values * * @return object */ public function create(array $values) { $sets = $this->formatColumnValueArray($values); $sql = "INSERT INTO " . $this->table . " SET " . implode(", ", $sets); $this->dbh->exec($sql); $id = $this->dbh->lastInsertId(); $obj = $this->find($id); return $obj; }
public function insertId() { $this->init(); $id = $this->dblol->lastInsertId(); if ($id > 0) { return $id; } return false; }
public function insert($data) { $stmt = $this->pdo->prepare('INSERT INTO users (data) values (:data)'); if (!is_string($data)) { $data = json_encode($data); } $stmt->bindValue('data', $data); $stmt->execute(); return $this->pdo->lastInsertId(); }
/** * Insert new tag into database. * * @param $tag Tag * @return bool */ public function insert($tagValue) { $tag = new Tag(); $tag->setValue($tagValue); $query = $this->db->prepare("INSERT INTO tags (value) VALUES(:tag_value)"); $query->bindValue(":tag_value", $tagValue); $query->execute(); $tag->setId($this->db->lastInsertId()); return $tag; }
/** * @param string $sql * @return bool|string */ public function create($sql = '') { if (strlen($sql) > 0) { $sth = $this->pdo->query($sql); if ($sth) { return $this->pdo->lastInsertId(); } } return false; }
/** * @return bool */ public function save() { $sql = $this->{'get' . ($this->exists() ? 'Update' : 'Insert') . 'Sql'}(); $stmt = self::$db->prepare($sql); $bool = $stmt->execute($this->exists() ? $this->values : $this->getValuesWithoutPk()); if (!$this->exists()) { $this->values[static::$pk] = self::$db->lastInsertId(); } return $bool; }
/** * @param string , $sql * @param array $sub * @return bool */ public function execute($sql, $sub = []) { $sth = $this->dbh->prepare($sql); $res = $sth->execute($sub); if (false != $res) { $this->lastInsertID = $this->dbh->lastInsertId(); $this->rowCount = $sth->rowCount(); } return $res; }
/** * {@inheritdoc} */ public function save(User $user) { $stmt = $this->pdo->prepare('INSERT INTO users(`name`, `email`, `password`) VALUES (:name, :email, :password)'); $result = $stmt->execute(['name' => $user->getName(), 'email' => $user->getEmail(), 'password' => $user->getPassword()]); if (!$result) { throw new RuntimeException('Unable to save User Entity! ' . $stmt->errorInfo()[2]); } $this->idSetter->setEntityId($user, (int) $this->pdo->lastInsertId()); return $user; }
public function saveSitemap($baseurl) { //$sitemapXmlPath = $baseurl . '/sitemap.xml'; $sitemapXmlPath = cfg('TEST_SITEMAP_XML'); $sitemap = new SimpleXMLElement($sitemapXmlPath, null, true); $this->insertOrUpdate($baseurl, ''); $parentId = $this->db->lastInsertId(); foreach ($sitemap as $url) { $this->insertOrUpdate($url->loc, $url->lastmod, $parentId); } }
private function Execute() { $this->Connect(); try { $this->Create->execute($this->Dados); $this->Result = $this->Conn->lastInsertId(); } catch (PDOException $e) { $this->Result = null; WSErro("<b>Erro ao cadastrar:</b> {$e->getMessage()}", $e->getCode()); } }
private function Execute() { $this->Connect(); try { $this->create->execute($this->dados); $this->result = $this->conn->lastInsertId(); } catch (PDOException $e) { $this->result = null; echo "<b>Erro ao cadastrar:</b> {$e->getMessage()}"; } }
function bookInsertion($title, $ISBN, $author) { $query = 'INSERT INTO book (title, isbn, author_id) VALUES (?, ?, ?)'; $stmt = $this->con->prepare($query); $stmt->bindParam(1, $title); $stmt->bindParam(2, $ISBN); $stmt->bindParam(3, $author['id'], \PDO::PARAM_INT); $stmt->execute(); $book = ['id' => $this->con->lastInsertId(), 'title' => $title, 'isbn' => $ISBN, 'author' => $author]; return $book; }
/** * @param $post * @return false|Post */ public function create($post) { $sql = "INSERT INTO posts (user_id, message , created_at ,updated_at) values (:user_id, :message, now(), now())"; $stmt = $this->dbh->prepare($sql); $stmt->bindParam(':user_id', $post['user_id']); $stmt->bindParam(':message', $post['message']); $this->dbh->beginTransaction(); $stmt->execute(); $post = $this->findByID($this->dbh->lastInsertId()); $this->dbh->commit(); return $post; }
/** * Save record * @param array $data * @return int - last insert id */ public function save(array $data) { $sql = 'INSERT INTO `' . $this->_name . '` SET '; $names = array_keys($data); foreach ($names as $name) { $sql .= '`' . $name . '`=:' . $name . ', '; } $sql = rtrim($sql, ', '); $sth = $this->_connection->prepare($sql); $sth->execute($data); return $this->_connection->lastInsertId(); }
/** * * @param string $pickupAddress * @param string $shippingAddress * * @return integer order id */ public function execute($pickupAddress, $shippingAddress) { $insert = "INSERT INTO orders (id, pickup_address, shipping_address, paid_amount, shipping_amount) \n VALUES (:id, :pickupAddress, :shippingAddress, :paidAmount, :shippingAmount)"; $stmt = $this->db->prepare($insert); $stmt->bindValue(':id', NULL, \PDO::PARAM_NULL); $stmt->bindValue(':pickupAddress', $pickupAddress, \PDO::PARAM_STR); $stmt->bindValue(':shippingAddress', $shippingAddress, \PDO::PARAM_STR); $stmt->bindValue(':paidAmount', 0, \PDO::PARAM_INT); $stmt->bindValue(':shippingAmount', 0, \PDO::PARAM_INT); $stmt->execute(); return $this->db->lastInsertId(); }
public function insert($table, $data) { $args = []; foreach ($data as $k => $v) { $args[':' . $k] = $v; } $sql = sprintf("INSERT INTO %s(%s) VALUES(%s)", $table, implode(',', array_keys($data)), implode(',', array_keys($args))); //echo $sql; $sth = $this->con->prepare($sql); $sth->execute($args); return $this->con->lastInsertId(); }
public function testSimpleDeletion() { $this->PDO->exec('INSERT INTO `runalyze_training` (`accountid`) VALUES (0)'); $firstID = $this->PDO->lastInsertId(); $this->PDO->exec('INSERT INTO `runalyze_training` (`accountid`) VALUES (0)'); $secondID = $this->PDO->lastInsertId(); $this->insert(array(Object::ACTIVITYID => $firstID)); $this->insert(array(Object::ACTIVITYID => $secondID)); $this->delete($firstID); $this->assertEquals(false, $this->fetch($firstID)); $this->assertNotEquals(false, $this->fetch($secondID)); }