PHP - 结果集数组的访问值

So as normal PHP query returns an array it's never been explained to me how you actually extract the value from the query out.

    $countThemes = Singlequery('SELECT COUNT(1) FROM items WHERE type = :type',
                            array(':type' => 'theme'), $conn);

This is my query and it returns;

Array
(
    [0] => Array
        (
            [COUNT(1)] => 5
        )
)

I need the value 5 so far I've setup this below but I'm not sure what to call because I can't call a column name like a normal Select * query.

<?php foreach ($countThemes as $countTheme) : ?>
     <a href="#" class="btn view-all">View All <?= $countTheme['name']; ?></a>
<?php endforeach; ?>

2个回答

Use an alias for the return of the COUNT function:

$countThemes = Singlequery('SELECT COUNT(1) AS num_items FROM items WHERE type = :type',
                            array(':type' => 'theme'), $conn);

Then, your array should have the index num_items instead of COUNT(1).

This will also work :

echo $result[0]['COUNT(1)'];

However, using an alias in the SQL query - as suggested by nickb - is more elegant in my opinion.

展开翻译

译文



这也有效:</ p>

  echo $ result [0] ['COUNT  (1)']; 
</ code> </ pre>

但是,在我看来,使用SQL查询中的别名 - 正如nickb所建议的那样 - 更优雅。</ p> \ n </ div>

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问