2012-05-23 23 views
0

當試圖運行此代碼時,Cake在我們的foreach循環中拋出一個錯誤,我將包含模型,控制器和視圖。此代碼的最終目標是打印出用戶自己的發票,而不是數據庫中的所有發票。cakephp foreach error

模型

<?php 
    class Invoice extends AppModel{ 
    var $name='invoice'; 
    public $useTable = 'invoices'; 
    public $primaryKey = 'id';} 

控制器與相關職能

<?php 

class InvoicesController extends AppController{ 

    public function index(){ 
      $this->set('title_for_layout', 'indexPage'); 
     } 


public function payinvoice($id = null){ 
     $this->set('title_for_layout', 'Pay Invoice'); 
     $this->set('stylesheet_used', 'homestyle'); 
     $this->set('image_used', 'eBOXLogoHome.jpg'); 
     $this->layout='home_layout'; 


     $this->set('invoice', $this->Invoice->read(null, $id)); 
} 

public function viewinvoice(){ 
     $this->set('title_for_layout', 'View invoice'); 
     $this->set('stylesheet_used', 'homestyle'); 
     $this->set('image_used', 'eBOXLogoHome.jpg'); 
} 

視圖文件

<table width="100%" border="1"> 

      <table width="100%" border="1"> 
       <tr> 
        <th>Biller</th> 
        <th>Subject</th> 
        <th>Date</th> 
        <th>Action</th> 
       </tr> 
      <?php foreach($invoice as $invoice): ?> 
      <tr><td align='center'> 
<?php echo $this->Html->link($invoice['Invoice']['biller'], 
array('action' => 'viewinvoice', $invoice['Invoice']['id'])); ;?> </td> 
<td align='center'><?php echo $invoice['Invoice']['subject']; ?></td> 
<td align='center'><?php echo $invoice['Invoice']['datecreated']; ?></td> 
<td align='center'><a href="viewinvoice"><button>View Invoice</button></a><a href="disputeinvoice"><button>Dispute Invoice</button></a></td> 
</tr><?php endforeach; ?> 

      </table> 
+0

你嘗試過像...在'foreach'使用不同的變量名稱爲'as'? –

+0

它會拋出一個意見,說foreach行意外的T_String – user1393064

+2

'foreach($ invoice as $ invoice):'??? XD加油!你知道這個問題有什麼問題= P – pleasedontbelong

回答

1

,我看到一對夫婦的問題與您的代碼,你應該清楚這些,然後再試一次(我不認爲這個錯誤是像你說的那樣在每條線上)

class Invoice extends AppModel{ 
    var $name='invoice'; 
    public $useTable = 'invoices'; 
    public $primaryKey = 'id'; 
} 

所有正在定義這裏的屬性是默認值,所以沒有必要去界定,可能需要被var $name如果你正在使用PHP 4的唯一一個,否則你的模型可能僅僅是:

class Invoice extends AppModel{ } 

其次,儘量不要命名您的foreach迭代變量一樣的數組你迭代,這可能可能是原因您的問題。我個人傾向於調用數組$items,然後它裏面的每個元素$item

<?php foreach($invoices as $invoice): ?> 

這樣,你不小心將覆蓋原來的數組中的東西...

2

幾點:

foreach($invoice as $invoice): 

應該是:

foreach($invoices as $invoice): 

正如其他一些人所提到的。

但是根本的問題是,您讀入$ invoice的數據結構是一條記錄,而不是多條記錄的數組。

可以廢除在foreach一起: