0

我制作了一个代码来生成 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_controller.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')); 
    }   
}

问题:代码生成所有随机数,但我的代码有问题,仅插入最后一个随机数而不是全部,我想插入所有随机数

谢谢

4

4 回答 4

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));
于 2012-05-01T08:35:05.510 回答
1

将以下行移出循环

 $this->Session->setFlash("Epin has been added");
 $this->Redirect(array('action'=>'admin_create_epin')); 

它会起作用的

于 2012-05-01T08:29:49.047 回答
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']通过数组访问您的所有号码。并且不要从循环中重定向。

于 2012-05-01T08:28:34.673 回答
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')); 
于 2012-05-01T08:35:53.630 回答