如何在twig文件中显示行计数结果

时间:2015-06-24 06:50:33

标签: mysql symfony twig

我在存储库中获取行计数,并且该查询返回一个数组作为结果。如何获取数字计数并在我的树枝文件中显示结果?

这是查询行计数:

public function getTrailCount(){

    $sql = "SELECT count(`id`)  FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";

    $stmt = $this->connection->prepare($sql);
    $stmt->execute();
    $trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
    //$trailCount->getSingleScalarResult();

    //echo '<pre>'; print_r($trailCount); exit;

    return $trailCount;
}

在控制器中我试图像这样获取它,但我知道它的程序错误:

foreach($trailCount as $trail){

        $data['trailCount'] = $trail->count; //throughing an error

    }

如何修改此代码,非常感谢任何帮助。感谢

2 个答案:

答案 0 :(得分:0)

在这种情况下,使用PDO::FETCH_NUM会更简单:

$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
foreach($trailCount as $trail){
    $data['trailCount'] = $trail[0]; // Using "0" instead of named key
}

但如果您仍然真的想使用FETCH_ASSOC,则需要:

$sql = "SELECT count(`id`) as cnt  FROM `article ...... "
.....

foreach($trailCount as $trail){
    $data['trailCount'] = $trail['cnt'];
}

请注意,我没有使用->cnt而是['cnt'],因为从PDO返回的数据不是基于对象的,而是基于数组的。

希望这有点帮助...

编辑:

由于缺少Twig部分,我只能假设你要做的事情:

/**
 * @Route("/foo")
 * @Template()
 */
public function fooAction(){
    ...
    ... The code above
    ...

    return array('data' => $data);
}

然后,在你的树枝上:

{{ data.trailCount }}

答案 1 :(得分:0)

我在Jovan Perovic的帮助下得到了解决方案,我确实喜欢这个:

查询部分:

if (... < 480)
{
menu1.Visible = false;
menu2.Visible = true;
}

if (... > 481)
{
menu1.Visible = true;
menu2.Visible = false;
}
控制器中的

public function getTrailCount(){

$sql = "SELECT count(`id`) as cnt  FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";

$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);

return $trailCount[0]['cnt']; //instead of an array i passed the single value
}

在twig文件中我直接显示了值:

$trailCount = $clicknblog->getTrailCount();
return $this->render('AdventureBiddingBundle:Organiser:editProfileOrganiser.html.twig', array(                   
                'trails' => $trailCount

            ));

希望这有助于遇到同样问题的人