我想用一些票 ID 初始化一个“票”表。为此,我想在表中插入 120 个工单 ID。但是,在每 10 条语句中,MySQL 都会告诉我 ID 已经存在,因此不会让我插入它。这是我的代码:
//make a query
$insert_ticket_query = "INSERT INTO ticket (id) VALUES (?)";
$insert_ticket_stmt = $mysqli->stmt_init();
$insert_ticket_stmt->prepare($insert_ticket_query);
$insert_ticket_stmt->bind_param('s', $ticket_id);
$mysqli->autocommit(FALSE); //start transaction
for($i=0;$i<NO_GUESTS;$i++){
$id = generate_id($i);
$ticket_id = format_id($id, $prefix['ticket'], $suffix['ticket']);
$t_id = $ticket_id;
//echo '<p>'.$ticket_id.'</p>';
$result = $mysqli->query("SELECT * FROM ticket WHERE id='".$ticket_id."'");
$row_count = $result->num_rows;
if($row_count == 0){
$result->close();
if($insert_ticket_stmt->execute()){
$mysqli->commit();
echo "<p>".$t_id."added to the ticket table!</p>";
}
else{
$mysqli->rollback();
echo "problem inserting'".$t_id."' to the ticket table";
}
}
else{
echo "<p>".$t_id."already exists, so not adding it!</p>";
$result->close();
}
}
$mysqli->autocommit(TRUE);
$insert_ticket_stmt->close();
?>
以下是代码中使用的函数:
function generate_id($integer){
//generate an ID based on the $string parameter
//$id = "000000000000XZLH";
$string = (string) $integer;
$length = strlen($string);
$id_string = "10000000";
for($i=0;$i<$length;$i++)
$id_string[$i] = $string{$i};
return $id_string;
}
function format_id($id_string, $id_prefix, $id_suffix){
$id = "0000000000000000";
//apply the prefix
for($i=0;$i<4;$i++)
$id[$i] = $id_prefix{$i};
//apply the id
for($i=4,$j=0;$j<8;$i++,$j++)
$id[$i] = $id_string{$j};
//apply the suffix
for($i=12,$j=0;$j<4;$i++,$j++)
$id[$i] = $id_suffix{$j};
return $id;
}
这是返回到浏览器的日志:
TCKT00000000YDLO已添加到票务表中!
TCKT10000000YDLO 已添加到票务表中!
TCKT20000000YDLO 已添加到票务表中!
TCKT30000000YDLO 已添加到票务表中!
TCKT40000000YDLO已添加到票务表中!
TCKT50000000YDLO已添加到票务表中!
TCKT60000000YDLO已添加到票务表中!
TCKT70000000YDLO已添加到票务表中!
TCKT80000000YDLO已添加到票务表中!
TCKT90000000YDLO 已添加到票务表中!
TCKT10000000YDLO已经存在,所以不加了!
TCKT11000000YDLO 已添加到票务表中!
TCKT12000000YDLO 已添加到票务表中!
TCKT13000000YDLO已添加到票务表!
TCKT14000000YDLO已添加到票务表中!
TCKT15000000YDLO已添加到票务表中!
TCKT16000000YDLO已添加到票务表中!
TCKT17000000YDLO 已添加到票务表中!
TCKT18000000YDLO已添加到票务表中!
TCKT19000000YDLO 已添加到票务表中!
TCKT20000000YDLO已经存在,所以不加了!