Setting a unique identifier for a row in a MySQL database

I want to set a unique identifier for each item that is added to my database, similar to Drupal nodes. Just not sure how I find out what will be the next number when adding a new item to my database. The status of MySQL is:

$query = "INSERT INTO `HERDSIRES`(uid, name, color, gender) VALUES ( VALUE of next uid, '$name', '$color',  '$gender')";

I mean, I need to query the database before INSERT and find out what the value of the last UID is, then add 1 to it, and then save it to a variable. I'm just not sure if this is the best way.

Any thoughts?

+3
source share
4 answers

If the column is set to auto-generate against the database, you can simply pass nullin the instructions INSERT, and MySQL will do the rest.

, auto_increment.

:

INSERT INTO `HERDSIRES`(uid, name, color, gender) 
VALUES ( null, '$name', '$color',  '$gender')";

, :

INSERT INTO `HERDSIRES`(name, color, gender) 
VALUES ( '$name', '$color',  '$gender')";

edit: , PHP :

$query = mysql_query('INSERT INTO ...');
$new_row_id = mysql_insert_id();

// do something with $new_row_id
+6

, autoincrement? SQL .

+2

, .

+1

:

For LAST_INSERT_ID () , the most recently generated identifier is stored in the server for each connection. It does not change by another client. It does not even change if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL, not 0). Using LAST_INSERT_ID () and AUTO_INCREMENT columns from multiple columns at the same time, clients are perfectly faithful. each client will receive the last inserted ID for the last statement that the client is running.

+1
source

Source: https://habr.com/ru/post/1784889/


All Articles