How to generate unique tag_id start from F-00001 in php

你说的曾经没有我的故事 提交于 2021-01-29 05:00:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!