PHP/MySQL insert row then get 'id'

前端 未结 10 933
臣服心动
臣服心动 2020-11-22 16:03

The \'id\' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.

I would do it just as I said it, but is there a way I c

10条回答
  •  心在旅途
    2020-11-22 16:41

    As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See @Luke's answer for MySQLi). To do this with PDO, proceed as following:

    $db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
    $statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
    $statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
    
    echo $db->lastInsertId();
    

提交回复
热议问题