Geek
Geek

Reputation: 8320

Get id of last inserted row in PHP

I use PHP for server side scripting and mysql server for database. If I use mysql_insert_id() then it gives "0" and use of LAST_INSERT_ID() causes error "object returned empty description".This error I see when I debug on client-side in objective-C. My table's id column is auto generated. I dont' pass id explicitly.

Below is the PHP code :

 // Connect to our database
    $db = Frapi_Database::getInstance();

    $sql = "INSERT INTO userTrip 
        (userId, fromLat, fromLon, fromLoc, fromPOI,
        toLat, toLon, toLoc, toPOI,
        tripFinished, isMatched, departureTime, createdAt)
        values 
        (".$userId.",".$fromLat.",".$fromLon.", GeomFromText('POINT($fromLat $fromLon)')".",'".$fromPOI."',".$toLat.","
            .$toLon.", GeomFromText('POINT($toLat $toLon)')".",'".$toPOI."',0,0,'".
            $departureTime."','".date('Y-m-d H:i:s')."')";

    $stmt = $db->prepare($sql);        

    if (!$stmt->execute())
        throw new Frapi_Error('ERROR_INSERTING_RECORD');

    $lastId = LAST_INSERT_ID();
    $this->data['tripId'] = $lastId;
    $db = null;

Upvotes: 1

Views: 11568

Answers (5)

Naveen1425
Naveen1425

Reputation: 11

If your table have AUTO INCREMENT column like UserID,Emp_ID,.. then you can use this query to get last inserted record

SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)

In PHP code:

$con = mysqli_connect('localhost', 'userid', 'password', 'database_name');
if (!$con) {
     die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)";
$result = mysqli_query($con, $sql);

Then you can use fetched data as your requirement

Upvotes: 0

GautamD31
GautamD31

Reputation: 28763

Try with

$id = mysql_insert_id();

it will work for you,try this link mysql_insert_id and this

Upvotes: 0

Kovge
Kovge

Reputation: 2019

Try this (if you use mysqli):

 $db->insert_id;

Or (if you use PDO):

 $db->lastInsertId();

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173522

Frapi Database extends from PDO, so you would use this:

$lastId = $db->lastInsertId();

See also: PDO::lastInsertId()

Upvotes: 4

Dino Babu
Dino Babu

Reputation: 5809

are you looking for this ?

to get the last inserted id

mysql_insert_id();

mysql_insert_id

Upvotes: 0

Related Questions