幕布斯6054654
我创建了一个示例。从测试数据库和表结构开始:-- Database: `serials`DROP TABLE IF EXISTS `serial`;CREATE TABLE IF NOT EXISTS `serial` ( `id` int(10) NOT NULL AUTO_INCREMENT, `serial` varchar(100) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;创建一个db.php文件来连接数据库:function connect(){ $dsn = 'mysql:host=localhost;port=3306;dbname=serials'; try{ return new PDO($dsn, 'root', ''); }catch( \Exception $e ){ echo $e->getMessage(); exit; }}如果您还没有准备好插入并且只想向用户显示一个独特的序列号,我创建了form.php并执行了以下操作:<?phprequire_once('./db.php'); function createSerial() { $timestamp = time() . rand(10000, 99999); for($i=1;$i<=strlen($timestamp);$i++){ $piece = substr($timestamp, $i - 1, 1); $shuffle_array[] = $piece; } shuffle($shuffle_array); return implode('', $shuffle_array); } $pdo = connect(); //try up to 5 times for($i=0;$i<=4;$i++) { $serial_number = createSerial(); $sql = "SELECT * FROM serial WHERE serial = :serial"; $dbh = $pdo->prepare($sql); $dbh->execute( [ ':serial' => $serial_number ]); if( $dbh->rowCount() ) { $serial_number = ''; } }if( $serial_number) { ?><form action="form.php" method="post"> <div class="col-sm-9"> <input type="text" name="sn" value="AXJ<?php echo $serial_number; ?>" class="form-control" id="sn" placeholder="" readonly> </div><?php}?>还做了一个插入的例子:function createSerial() { $timestamp = time() . rand(10000, 99999); for($i=1;$i<=strlen($timestamp);$i++){ $piece = substr($timestamp, $i - 1, 1); $shuffle_array[] = $piece; } shuffle($shuffle_array); return implode('', $shuffle_array);}//database$pdo = connect();//try up to 5 timesfor($i=0;$i<=4;$i++) { $serial_number = createSerial(); $sql = "SELECT * FROM serial WHERE serial = :serial"; $dbh = $pdo->prepare($sql); $dbh->execute( [ ':serial' => $serial_number ]); if( ! $dbh->rowCount() ) { //insert $sql = "INSERT INTO serial VALUES ( :id, :serial)"; $dbh2 = $pdo->prepare($sql); $dbh2->execute([ ':id' => null, ':serial' => $serial_number ]); break; }}