2012-05-01 30 views
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_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

不挑剔,但我不會相信你的號碼。如果你需要一個很好的隨機分配,請使用一個經過驗證的隨機生成器,不要發明自己奇怪的操作。這是一個更好的隨機方法:'str_pad((string)mt_rand(0,99999999999),11,'0',STR_PAD_LEFT)' –

+0

好的解決方案Emil! – freshnode

+0

感謝@EmilVikström好的建議 –

回答

2

1)你必須移動Redirect() outsite循環。

2)在第一個$this->Epin->save(...)之後,最後一個插入的標識被存儲在$this->Epin->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)); 
+0

非常感謝,它爲我工作 –

+1

添加行之後,這個$ - > Epin-> id = null;代碼正在工作 –

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']數組。並且不要從循環中重定向。

+0

感謝回覆的,我m到處THT錯誤後用你的代碼[]不支持串 –

+0

看到我的編輯,你需要先轉換的變量作爲數組操作。 – freshnode

+0

收到這個錯誤 - >的preg_match()預計參數2爲字符串,數組給定 –

1

移動後的循環外線

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

,將工作

+0

感謝答覆,後做URL從來沒有開放,這不是解決 –

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'));