5

I need to get the id(AUTO-INCREMENTED) of latest inserted record in a table. I am using fat-free-framework.

I tried to get the latest id by using

$id = mysql_insert_id();

but it gave me this error

Access denied for user 'root'@'localhost' (using password: NO)

I am accessing database using fat-free-framework and not using traditional php functions. Can any one guide me how to accomplish this ?

Amarnath Balasubramanian
  • 8,498
  • 7
  • 30
  • 59
Umair
  • 301
  • 4
  • 19

4 Answers4

11

Try this code after record inserted

$id = $db->lastInsertId();
Kumar V
  • 8,669
  • 8
  • 37
  • 55
1

Beside kumar_v's answer, F3 will automatically populate $db->_id after a successfull insert.

sascha
  • 4,591
  • 3
  • 34
  • 51
  • 1
    A leading underscore usually indicates something "internal" or potentially "private", which implementation might change in the future. I'd better go with @kumar_v solution, even if it's probably not anything more than a wrapper around `$db->_id`. But since you never know... – Seether Sep 25 '15 at 09:29
1

Note that if you have used the SQL Mapper to create the row in your table, you can just do

$object->id;

Example (using a table containing quotes):

$quote = new DB\SQL\Mapper($db, 'quotes');
if($_POST){
    //overwrite with values just submitted
    $quote->copyFrom('POST');
    $quote->save();
    die("new quote added with id:".$quote->id);
}
pixeline
  • 17,191
  • 10
  • 79
  • 105
0
$quote = new DB\SQL\Mapper($db, 'quotes');
$quote->get('_id');

which '_id' is the id auto increment id field of your table, replace '_id' with yours you can read the docs : https://fatfreeframework.com/3.6/sql-mapper#get

samehanwar
  • 1,739
  • 2
  • 9
  • 18