>我已经制作了一个代码来生成 11 位随机数,我想将所有数字保存在数据库中
admin_create_epin.ctp(查看)
<tr>
Add E-pin:(No of E-Pin)
<td><?php echo $this->Form->input('e_pin',array('label'=>false));?></td>
</tr>
epins_controlller.php
public function admin_create_epin(){
$limit = $this->data['Epin']['e_pin'];
for($i=0;$i<$limit;$i++)
{
$random = substr(number_format(time() * rand(),0,'',''),0,11)."<br/>";
$this->data['Epin']['e_pin'] = $random;
//pr($this->data); it's show all random number
$this->Epin->save($this->data); // i have problem only here it's save only last random number
$this->Session->setFlash("Epin has been added");
$this->Redirect(array('action'=>'admin_create_epin'));
}
}
问题:代码生成所有随机数,但我的代码中遇到问题,仅插入最后一个随机数而不是全部,我想插入所有随机数
谢谢
1)你必须Redirect()
向外移动循环。
2) 在第一个$this->Epin->save(...)
最后一个插入的 id 存储在 $this->Epin->id
中后,然后用于更新具有此 id 的记录以进行后续迭代。因此,您将只插入一条记录,并在上次迭代中重写。
保存前重置它:
for($i=0;$i<$limit;$i++)
{
//...
$this->Epin->id = null; // <- force insert in the next save
$this->Epin->save($this->data); // i have problem only here it's save only last random number
//...
}
您也可以尝试create()
方法:
$this->Epin->save($this->Epin->create($this->data));
将
以下行移出循环
$this->Session->setFlash("Epin has been added");
$this->Redirect(array('action'=>'admin_create_epin'));
它会工作
试试这个:
public function admin_create_epin(){
$limit = $this->data['Epin']['e_pin'];
$this->data['Epin']['e_pin'] = array(); // assign this to be an array first.
for($i=0;$i<$limit;$i++)
{
$random = substr(number_format(time() * rand(),0,'',''),0,11)."<br/>";
$this->data['Epin']['e_pin'][] = $random; // this pushes the value onto the end of the array 'e_pin'
//pr($this->data); it's show all random number
$this->Epin->save($this->data); // i have problem only here it's save only last random number
}
$this->Session->setFlash("Epin has been added");
$this->Redirect(array('action'=>'admin_create_epin'));
}
通过$this->data['Epin']['e_pin']
数组访问所有号码。并且不要从循环重定向。
更改行:$this->data['Epin']['e_pin'][$i] = $random;
而不是$this->data['Epin']['e_pin'] = $random;
并将以下行移出循环
$this->Session->setFlash("Epin has been added");
$this->Redirect(array('action'=>'admin_create_epin'));