我正在学习php。
我有一个mysql查询选择函数。
比我在foreach列表中使用它..
但只有当foreach在函数内部时它才有效。 我不知道如何让它在功能之外工作..
我做错了什么?
工作代码 - https://phpbox.info/d3GCP
没有工作代码:
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
$apps= $db->loadObjectList();
}
$apps = volaco();
?>
<table >
<?php if (count($apps)) : foreach ($apps as $app) : ?>
<tr >
<td width="40%"><?php echo $app->name; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td>
<td width="20%" style="text-align: center;"><?php echo $app->published; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td>
</tr>
<?php endforeach; else : ?>
<?php endif; ?>
</table>
非常感谢
答案 0 :(得分:1)
答案 1 :(得分:0)
在你的volaco()函数中添加一个返回值,$ apps超出范围。
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
return $db->loadObjectList();
?>
答案 2 :(得分:0)
试试这个:
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
$apps= $db->loadObjectList();
return $apps;
}
$apps = volaco();
?>
<table >
<?php if (count($apps)) : foreach ($apps as $app) : ?>
<tr >
<td width="40%"><?php echo $app->name; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td>
<td width="20%" style="text-align: center;"><?php echo $app->published; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td>
</tr>
<?php endforeach; else : ?>
<?php endif; ?>
</table>