PHP/MySQL insert row then get 'id'

前端 未结 10 936
臣服心动
臣服心动 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:45

    $link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
    mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
    $id = mysqli_insert_id($link);
    

    See mysqli_insert_id().

    Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.

提交回复
热议问题