last inserted id

422 views
Skip to first unread message

Muhammad Shahzad

unread,
Jun 15, 2017, 5:07:00 AM6/15/17
to f3-fra...@googlegroups.com

Hi,

How can I get last inserted id?

Initializing database connection in index.php


$f3->set("db.instance", new DB\SQL(
   
"mysql:host=" . $f3->get("db.host") . ";port=" . $f3->get("db.port") . ";dbname=" . $f3->get("db.name"),
    $f3
->get("db.user"),
    $f3
->get("db.pass")
));






Here is my code in controller:



$sql = "INSERT into table ...."
$res
= $f3->get('db.instance')->exec($sql);
print_r
($res); // always display me 1

echo $res
->id; //Trying to get property of non-object

Vester

unread,
Jun 15, 2017, 6:53:23 PM6/15/17
to Fat-Free Framework
You should use:

$id = $f3->get('db.instance')->lastInsertId();

$f3->get('db.instance') is a F3 SQL object and it forwards all non-implemented methods to the underlying PDO object ($this->pdo) via __call()

Muhammad Shahzad

unread,
Jun 15, 2017, 10:31:22 PM6/15/17
to Fat-Free Framework
Hi,

Thank you for your reply.

Is it reliable method? I meant once I insert the record and at the same time someone else do the same thing, so last insert id will not mix up?

Muhammad Shahzad

unread,
Jun 15, 2017, 10:32:55 PM6/15/17
to Fat-Free Framework
Is there any other method to insert record using insert query instead of calling exec function or sql mapper class?

Vester

unread,
Jun 16, 2017, 5:11:14 AM6/16/17
to Fat-Free Framework
It's unlikely, but it could happen.

To avoid this, you can use transactions. Just set the table engine to one that supports transactions (e.g InnoDB) and wrap your SQL sentences between $f3->get('db.instance')->begin() and $f3->get('db.instance')->commit(); the lastInsertId() must be placed before commit().

Vester

unread,
Jun 16, 2017, 5:21:20 AM6/16/17
to Fat-Free Framework
Well, exec() uses PDO and SQL Mapper too.

If your DB engine is MySQL/MariaDB, you can use MySQLi extension (http://php.net/manual/en/book.mysqli.php). PDO is more universal: the same class works for several DB Engines.

If you don't need the 'id' values to be in strict sequential order as natural numbers (autoincrement), you can generate the 'id' yourself before the insert based on microtime(), a time based UUID or a random hash. Then you supply the generated 'id' to the insert query with other values.

Muhammad Shahzad

unread,
Jun 16, 2017, 1:04:45 PM6/16/17
to Fat-Free Framework
Thank you, informative.
Reply all
Reply to author
Forward
0 new messages