本文整理汇总了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();
}
示例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');
}
示例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;
}
示例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);
}
}
示例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();
}
示例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;
}
示例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();
}
示例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;
}
示例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();
}
示例10: lastInsertId
public function lastInsertId()
{
try {
return $this->pdo->lastInsertId();
} catch (\PDOException $ex) {
throw new \SNDatabase\ConnectionFailedException($ex->errorInfo[2], $ex->getCode(), $ex);
}
}
示例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());
}
}
示例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());
}
}
示例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();
}
示例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;
}
示例15: insertId
public function insertId()
{
$this->init();
$id = $this->dblol->lastInsertId();
if ($id > 0) {
return $id;
}
return false;
}