How do I get the last inserted ID of a MySQL table in PHP?

后端 未结 16 2287
温柔的废话
温柔的废话 2020-11-21 23:09

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?

Is it similar to SELECT MAX(id) FROM

相关标签:
16条回答
  • 2020-11-21 23:43

    To get last inserted id in codeigniter After executing insert query just use one function called insert_id() on database, it will return last inserted id

    Ex:

    $this->db->insert('mytable',$data);
    echo $this->db->insert_id(); //returns last inserted id
    

    in one line

    echo $this->db->insert('mytable',$data)->insert_id();
    
    0 讨论(0)
  • 2020-11-21 23:43

    Using MySQLi transaction I sometimes wasn't able to get mysqli::$insert_id, because it returned 0. Especially if I was using stored procedures, that executing INSERTs. So there is another way within transaction:

    <?php
    
    function getInsertId(mysqli &$instance, $enforceQuery = false){
        if(!$enforceQuery)return $instance->insert_id;
    
        $result = $instance->query('SELECT LAST_INSERT_ID();');
    
        if($instance->errno)return false;
    
        list($buffer) = $result->fetch_row();
    
        $result->free();
    
        unset($result);
    
        return $buffer;
    }
    
    ?>
    
    0 讨论(0)
  • 2020-11-21 23:44

    It's ok to use mysql_insert_id(), but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session. If you use it otherwise it wouldn't work correctly.

    0 讨论(0)
  • 2020-11-21 23:45

    If you're using PDO, use PDO::lastInsertId.

    If you're using Mysqli, use mysqli::$insert_id.

    If you're still using Mysql:

    Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

    But if you have to, use mysql_insert_id.

    0 讨论(0)
  • 2020-11-21 23:45

    You can get the latest inserted id by the in built php function mysql_insert_id();

    $id = mysql_insert_id();
    

    you an also get the latest id by

    $id = last_insert_id();
    
    0 讨论(0)
  • 2020-11-21 23:45

    NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.

    The table:

    create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));

    Now if you do:

    insert into xyz (name) values('one'),('two'),('three');

    The mysqli::insert_id will be 1 not 3.

    To get the correct value do:

    mysqli::insert_id + mysqli::affected_rows) - 1

    This has been document but it is a bit obscure.

    0 讨论(0)
提交回复
热议问题