问题
How to generate unique tag_id start from F-00001 when insert date into item table using php and mysql.
This is my my table. I have three columns in my database table using MySQL.
CREATE TABLE item (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
tag_id VARCHAR(8) NOT NULL
)
回答1:
As @mickmackusa points out, you don't need to have this field in your database as you can automatically generate it from your auto-increment id
value. There are a number of ways to do this.
Use a generated column (MySQL 5.7 or later):
CREATE TABLE item (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
tag_id VARCHAR(8) AS CONCAT('F-', LPAD(id, 5, '0'))
)
Use a view:
CREATE VIEW item_view AS
SELECT *, CONCAT('F-', LPAD(id, 5, '0')) AS tag_id FROM item
Generate in PHP using str_pad:
// assume $row is an associative array of row of table
$tag_id = 'F-' . str_pad($row['id'], 5, '0', STR_PAD_LEFT);
来源:https://stackoverflow.com/questions/53128339/how-to-generate-unique-tag-id-start-from-f-00001-in-php