PHP/MySQL insert row then get 'id'

前端 未结 10 921
臣服心动
臣服心动 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 @NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.

    // First, connect to your database with the usual info...
    $db = new mysqli($hostname, $username, $password, $databaseName);
    // Let's assume we have a table called 'people' which has a column
    // called 'people_id' which is the PK and is auto-incremented...
    $db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
    // We've now entered in a new row, which has automatically been 
    // given a new people_id. We can get it simply with:
    $lastInsertedPeopleId = $db->insert_id;
    // OR
    $lastInsertedPeopleId = mysqli_insert_id($db);
    

    Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php

    0 讨论(0)
  • 2020-11-22 16:44

    I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php

    The answer is:

    mysql_query("INSERT INTO tablename (columnname) values ('$value')");        
    echo $Id=mysql_insert_id();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 16:48

    Try this... it worked for me!

    $sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
        if (mysqli_query($conn, $sql)) {
        $last_id = mysqli_insert_id($conn);
        $msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
    } else {
        $msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
    
    0 讨论(0)
提交回复
热议问题