Search code examples
phpmysqlmysql-insert-id

mysql_insert_id and my woes?


I'm trying to get the auto incremented column of a row. The code will explain, but basically I'm trying to insert a row into a table called orders, and then I want to get the auto incremented number. This is my PHP.


<?php

$db = DBConnection::connect();

$q = "INSERT INTO orders (customerid, orderdate) VALUES (".$customerid.", CURRENT_TIMESTAMP)";

$ps = $db->prepare($q);     
$ps->execute();
$db = null;

echo mysql_insert_id();
?>

At this stage all I really want to do is echo out the auto number.

This is my structure


CREATE TABLE `orders` (
  `orderid` int(25) NOT NULL AUTO_INCREMENT,
  `customerid` int(11) NOT NULL,
  `orderdate` date DEFAULT NULL,
  PRIMARY KEY (`orderid`),
  KEY `orderid` (`orderid`)
)

Any help would be greatly appreciated, thank you :)


Solution

  • PDO is different from mysql_* functions.

    Since you've used PDO, you must use the method lastInsertId() from the PDO object:

    $db->lastInsertId();