当前位置: 首页>>代码示例>>PHP>>正文


PHP PDO::lastInsertId方法代码示例

本文整理汇总了PHP中PDO::lastInsertId方法的典型用法代码示例。如果您正苦于以下问题:PHP PDO::lastInsertId方法的具体用法?PHP PDO::lastInsertId怎么用?PHP PDO::lastInsertId使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PDO的用法示例。


在下文中一共展示了PDO::lastInsertId方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: setUp

 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();
 }
开发者ID:9x,项目名称:Runalyze,代码行数:7,代码来源:InserterTest.php

示例2: insert

 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');
 }
开发者ID:venturabruno,项目名称:sistema_relatorio,代码行数:28,代码来源:DiarioDAO.php

示例3: __construct

 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;
 }
开发者ID:ifcanduela,项目名称:pew,代码行数:26,代码来源:DatabaseTest.php

示例4: save

 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);
     }
 }
开发者ID:riimu,项目名称:baremvc,代码行数:28,代码来源:Repository.php

示例5: insert_id

 /**
  * 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();
 }
开发者ID:scottleedavis,项目名称:hackazon,代码行数:12,代码来源:Connection.php

示例6: save

 /**
  * 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;
 }
开发者ID:jimdoescode,项目名称:alert.codemana.com,代码行数:32,代码来源:Users.php

示例7: setUp

 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();
 }
开发者ID:9x,项目名称:Runalyze,代码行数:7,代码来源:UpdaterTest.php

示例8: duplicateCategory

 /**
  * 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;
 }
开发者ID:GerDner,项目名称:luck-docker,代码行数:36,代码来源:CategoryDuplicator.php

示例9: insert

 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();
 }
开发者ID:AlexOrfen,项目名称:Schedule,代码行数:27,代码来源:db.php

示例10: lastInsertId

 public function lastInsertId()
 {
     try {
         return $this->pdo->lastInsertId();
     } catch (\PDOException $ex) {
         throw new \SNDatabase\ConnectionFailedException($ex->errorInfo[2], $ex->getCode(), $ex);
     }
 }
开发者ID:sndatabase,项目名称:pdo,代码行数:8,代码来源:PDOConnection.php

示例11: logStart

 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());
     }
 }
开发者ID:pombredanne,项目名称:ForgeUpgrade,代码行数:8,代码来源:Db.php

示例12: 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());
     }
 }
开发者ID:comelyio,项目名称:comely,代码行数:15,代码来源:AbstractPdo.php

示例13: execute

 /**
  * 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();
 }
开发者ID:alcyz,项目名称:alcys-orm,代码行数:14,代码来源:InsertFacade.php

示例14: create

 /**
  * 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;
 }
开发者ID:aronduby,项目名称:wheniwork,代码行数:16,代码来源:PDORepository.php

示例15: insertId

 public function insertId()
 {
     $this->init();
     $id = $this->dblol->lastInsertId();
     if ($id > 0) {
         return $id;
     }
     return false;
 }
开发者ID:voilab,项目名称:acedao,代码行数:9,代码来源:Database.php


注:本文中的PDO::lastInsertId方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。