如何在php中使用prepare语句获取insert_id?

时间:2017-12-05 11:44:46

标签: php mysql

我试过但我无法从函数中获取insert_id。我已经开了一个课堂电话,但我不明白我怎么能得到它。见下面的代码。

class DatabaseConnection {
protected $pdo;
public function __construct() {
 try {
   $this->pdo = new PDO('mysql:host=localhost;dbname=xxx', 'root', '');
 } catch(PDOException $e) {
  exit('Database error');
  }
 }
}

class Invoice extends DatabaseConnection {
  public function order($rename, $location) {
  $query = $this->pdo->prepare("INSERT INTO orderlist (re_name, location) VALUES (?, ?)");
  $query -> execute(array($rename, $location));
}

$user = new Invoice();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
   $rename = $_POST['re_name'];
   $location = $_POST['location'];
   $insertOrder  = $user->order($rename, $location); // call the function here
   $insertid = ____ // I want to get id using insert_id in here see blank space.
}

数据插入成功,但我如何获取最近插入数据的id。帮助我。

1 个答案:

答案 0 :(得分:2)

如果你尝试过,它会不会起作用:

$user->getPdo->lastInsertId();

Details