如何在php中从F-00001开始生成唯一的tag_id [英] How to generate unique tag_id start from F-00001 in php
本文介绍了如何在php中从F-00001开始生成唯一的tag_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在使用php和mysql将日期插入项目表时从F-00001开始生成唯一的tag_id.
How to generate unique tag_id start from F-00001 when insert date into item table using php and mysql.
这是我的桌子.我的数据库表中有三列使用 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
)
推荐答案
正如@mickmackusa 指出的,你不需要在你的数据库中有这个字段,因为你可以从你的自动增量 id 自动生成它
值.有很多方法可以做到这一点.
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.
使用生成的列(MySQL 5.7 或更高版本):
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'))
)
使用视图:
CREATE VIEW item_view AS
SELECT *, CONCAT('F-', LPAD(id, 5, '0')) AS tag_id FROM item
使用 str_pad
:
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);
这篇关于如何在php中从F-00001开始生成唯一的tag_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文