我正在尝试使用for循环将10条不同的记录插入数据库中,但它一直只插入最后一个生成的记录。我希望每个记录在每个循环中都插入到数据库中。 这是main.php代码
<?php
if(isset($_POST['generate_voucher_code'])){
//generate the number of codes
$number_to_generate = $_POST['gen_no'];
//echo $number_to_generate;
$v_cost = $_POST['amount'];
if($v_cost <= 500){
$dur = 15;
}
else{
$dur = 60;
}
//generate voucher
$date = date('y-m-dh:i:s');
for($i=1;$i<$number_to_generate + 1;$i++){
//Voucher code
$v_code= substr(md5($date),0,5);
//if voucher doesnt exist
if(!$user->check_voucher_code($v_code)){
//save code
$admin->save_voucher($v_code,$dur);
}
}
}
?>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form method="POST" class="form-inline">
<div class="form-group">
<select name="gen_no" class="form-control">
<?php
for($i=1;$i<11;$i++){?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<button class="btn btn-success" name="generate_voucher_code" style="border-radius:0;">Generate voucher code</button>
</div>
</form>
</div>
</div>
这是具有保存凭证功能的管理类
<?php
class Admin{
private $db;
function __construct($dbcon){
$this->db = $dbcon;
}
public function save_voucher($v_code,$dur){
try{
$stmt = $this->db->prepare("INSERT INTO voucher_codes(voucher_code,duration)
VALUES (:v_code,:dur)");
$stmt->bindParam(':v_code',$v_code);
$stmt->bindParam(':dur',$dur);
$stmt->execute();
return true;
}
catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
}