简体   繁体   中英

How to lock auto_increment value?

I have a query that returns the next auto-increment value (id), and I use that value when I'm inserting data in table t_name.

SELECT AUTO_INCREMENT id
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 't_name'

But I want that this query gives a different value each time. Eg Me and my pal are inserting data in db at same time, so I will get one id, he will get another. When I run this query, I want it to give me a different and incremented value each time.

Is it possible? Or do I have to create tables with sequences?

You can insert and than get the last inserted id:

    $connection  = mysqli_connect($rv, $username, $pass, $mydatabase);
    $result = $connection->query('INSERT INTO mytable (id, name) VALUES("", "myName")');
    if($result)
    {    $lastId = connection->insert_id;
         // so something with $lastId...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM