Is there a way to return the id of a row that was just created in MySQL with PHP?

前端 未结 6 1903
Happy的楠姐
Happy的楠姐 2021-01-19 09:52

When I create a new entry in my MySQL database, I\'d like the query to return the id of the table that was just created. If it cannot do this, is there another way to find

相关标签:
6条回答
  • 2021-01-19 10:19

    You mean last autoincrement id?

    <?php
    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('mydb');
    
    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf("Last inserted record has id %d\n", mysql_insert_id());
    ?>
    
    0 讨论(0)
  • 2021-01-19 10:21

    You have LAST_INSERT_ID() in My SQL (@@IDENTITY in ms sql) and mysql_insert_id in php.

    Personally though, I try to avoid auto increments / identity columns and generate my id's in other ways. Amongst other reasons, because they make inserts into multiple tables harder.

    /B

    0 讨论(0)
  • 2021-01-19 10:26

    Do you mean the ID of the record you have just inserted into a table, if so you are looking for mysql_insert_id.

    0 讨论(0)
  • 2021-01-19 10:27

    You want mysql_insert_id()

    0 讨论(0)
  • 2021-01-19 10:27

    have a look at http://us3.php.net/mysql_insert_id

    0 讨论(0)
  • 2021-01-19 10:29

    Use the mysql_insert_id function... http://php.net/mysql_insert_id

    Excuse the underscores converting the 'insert' into italics... follow the link and you should be fine.

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