2016-11-12 32 views
0

在此先感谢,我是cakephp新手,我使用的是cakephp2.8.5版本。其实我想编写一个php代码来计算从mysql数据库表中记录数量的记录,比较排序的日期列日期值和当前日期。我写了代码,但我的菜单在default.ctp页面。在订单检查菜单中,我必须以数字显示计数。 default.ctp页面位于app/view/Layout/default.ctp中,所以如何在不使用控制器的情况下在php代码中创建计数值。php代码不工作在CakePHP2.8.5的default.ctp页面

我的代码将比较当前日期与表列日期和计算count.How我可以通过变量$ ordCounts到default.thtml中页面,而无需创建控制器Page 这是如下:

<?php      

$a = 0; 

for($j=0; $j<count($ordCounts) ;$j++) 
{ 
    $orderDate = $ordCounts[$j]['carts']['order_date'];   
    $currentDate = $dateTime;   
    $diff = strtotime($currentDate) - strtotime($orderDate);   
    $hour = $diff/(60*60);        
    if($hour>24) 
    { 
     $a++;   
    } 
} 

echo $a; 

?> 
+0

你的意思是如何设置的变量上面的代码的函数控制器在default.ctp页面中使用? –

回答

2

AppController

public function beforeRender(){ 
    parent::beforeRender(); 
    //here your code 
    $this->set('a',$a); 
} 

$a变量创建beforeRender()方法将在模板中提供

+0

我已经测试,但它不工作 –

0

您可以创建一个计算在AppController中的出现次数这样

function countOccurences(){ 
    $a = 0; 
    for($j=0; $j<count($ordCounts) ;$j++) 
    { 
     $orderDate = $ordCounts[$j]['carts']['order_date'];   
     $currentDate = $dateTime;   
     $diff = strtotime($currentDate) - strtotime($orderDate);   
     $hour = $diff/(60*60);        
     if($hour>24) 
     { 
      $a++;   
     } 
    } 
    return $a; 
} 

,然后调用这个函数在你beforeFilterMethod在AppController的

function beforeFilter(){ 
    parent::beforeFilter(); 
    $count = $this->countOccurences(); 
    $this->set('count',$count); 
} 
+0

不,我在我的default.ctp页面出现一些错误。实际上,我在UsersController中创建了一个SQL查询,就像这个公共函数orderCount() { //对于24小时订单检查所有订单 $ counts = $ this-> User-> query(“select * FROM carts LEFT JOIN checking on carts.orderid = checks.order_id AND carts.exam_name = checks.exam WHERE checks.order_id is null AND checks.exam is null AND carts.order_date set('count',$ counts); } –

+0

在deafult.ctp页面中,我必须通过变量计数<?php $ a = 0; \t \t \t \t \t \t \t为($ J = 0; $Ĵ<计数($计数); $ J ++) \t \t \t \t \t \t \t { \t \t \t \t \t \t \t $ orderDate存储= $计数[ $ j]的[ '推车'] [ 'order_date的']; \t \t \t \t \t \t \t $ currentDate = $ dateTime; \t \t \t \t \t \t \t $ diff = strtotime($ currentDate) - strtotime($ orderDate); \t \t \t \t \t \t \t $ hour = $ diff /(60 * 60); \t \t \t \t \t \t \t如果($小时> 24) \t \t \t \t \t \t \t { \t \t \t \t \t \t \t $一个++; \t \t \t \t \t \t \t} \t \t \t \t \t \t \t} \t \t \t \t \t \t \t回美元; –

+0

,但我得到致命的错误,在行120 default.ctp页面 –