php - How to generate a student ID in PHP? And how to avoid goto?
问题描述
I want to generate a unique student ID. The format that I want is the last two digits of the current year plus 5 digits after that. For example: 2000001, 2000002, 2000003.. etc.. This is the extract of my code right now.
$pre = substr(strval(date("Y")),2);
$num = 1;
include "dbh.inc.php"; // this file merely creates the $conn variable that connects to mysql database.
$sql_cmd = "SELECT id FROM students WHERE id=?;";
$stmt = $conn->stmt_init();
if ($stmt) {
$prepare = $stmt->prepare($sql_cmd);
if ($prepare) {
bind:
$studentid = $pre . str_repeat('0', (4 - strlen($num)) ) . strval($num);
$bind = $stmt->bind_param('s', $studentid);
if ($bind) {
$result = $stmt->execute();
if ($result) {
$num++;
goto bind;
}
else {
// insert student here using $studentid
}
}
}
}
But I need to improve this because:
- It uses a goto (I want to avoid it)
- It seems overkill to prepare, bind, execute, etc everytime and query the database every loop.
- It is obviously slow.
Please let me know if there is a better way of doing this.
解决方案
您可以在 MySQL 端生成新的 id:
include "dbh.inc.php"; // this file merely creates the $conn variable that connects to mysql database.
$sql =
"SELECT CONCAT("
. "DATE_FORMAT(CURDATE(), '%y'), "
. "LPAD(COALESCE(MAX(RIGHT(id, 5)) + 1, 1), 5, '0')"
. ") AS new_id "
. "FROM students";
$result = $conn->query($sql);
if ($result) {
if ($row = $result->fetch_assoc()) {
// insert student here using $row['new_id']
}
}
或者另一种选择是在插入时创建触发器:
DELIMITER //
CREATE TRIGGER students_tr_bi BEFORE INSERT ON students
FOR EACH ROW
BEGIN
SET NEW.id = (
SELECT CONCAT(
DATE_FORMAT(CURDATE(), '%y'),
LPAD(COALESCE(MAX(RIGHT(id, 5)) + 1, 1), 5, '0')
) FROM students
);
END//
DELIMITER ;
-- Usage:
INSERT INTO students (name) VALUES ('John');
推荐阅读
- sql - 具有硬编码值的子查询的 LEFT OUTER JOIN 错误
- python - 没有正确输入数字 python selenium
- java - CollapsingToolbarLayout 的子级具有不同的折叠模式
- css - 具有已翻译项目的 Flexbox 列
- youtube - 让 youtube-dl 等到直播开始
- android - 有没有办法使用 snapshotListener 收听 Firestore 中新创建的文档
- javascript - 调用带有和不带有 promise 的异步函数
- reactjs - 代码上传后如何避免古腾堡崩溃?
- python - KivyMD MDFileManager 仅显示图像文件,如何列出所有文件类型?
- php - 输出 ID 不在 foreach 循环中的行