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 を使用してレコードを更新するために使用されます。したがって、挿入されるレコードは 1 つだけで、最後の反復で書き換えられます。

保存する前にリセットします。

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 に答える