我已经制作了一个代码来生成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'));
}
}
问题:代码生成所有随机数,但我的问题在我的代码插入只有最后一个随机数不是所有,我想插入所有随机数
感谢
答案 0 :(得分:2)
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));
答案 1 :(得分:1)
在循环外移动以下行
$this->Session->setFlash("Epin has been added");
$this->Redirect(array('action'=>'admin_create_epin'));
它会起作用
答案 2 :(得分:0)
试试这个:
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']
作为数组访问您的所有号码。并且不要从循环重定向。
答案 3 :(得分:0)
更改行:$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'));