php - 回显 SELECT COUNT(*) 查询的结果

标签 php mysql select count echo

在我的网站上,我在许多不同的设置中展示不同的产品,因此为了确保结果数量正确,我想用 PHP 来回显它们。到目前为止,我已经尝试按照我所知道的方式回应他们,但没有成功。

我想要回显的页面上的代码包含对顶部函数文件的要求。我尝试过:

<?php
//Call the count_stock() function
$result_count = count_stock();
?>
<p>Showing 1-9 of <?php echo $result_count['COUNT(*)']; ?> results.</p>
<p>Showing 1-9 of <?php echo $result_count[0]; ?> results.</p>
<p>Showing 1-9 of <?php print_r($result_count[0]); ?> results.</p>

我执行查询的函数是:

//create a function to count get_stock
function count_stock() {
    global $conn;
    //query the database to count the data entries in the stock table
    $sql = 'SELECT COUNT(*) FROM stock';
    //use a prepared statement to enhance security
    $statement = $conn->prepare($sql);
    $statement->execute();
    $result_count = $statement->fetchAll();
    $statement->closeCursor();
    return $result_count;
}

最佳答案

将您的功能更改为:

function count_stock() {
        global $conn;
        //query the database to count the data entries in the stock table
        $sql = 'SELECT COUNT(*) as tot FROM stock';
        //use a prepared statement to enhance security
        $statement = $conn->prepare($sql);
        $statement->execute();
        $result_count = $statement->fetch();
        $statement->closeCursor();
        return $result_count['tot'];
    }

关于php - 回显 SELECT COUNT(*) 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41326773/

相关文章:

php - 在 mysql 中存储搜索查询

android - Android App可以直接连接到在线mysql数据库吗

MySQL 一对多主选

mysql - 将 NOW() 设置为日期时间数据类型的默认值?

Mysql触发器错误

mysql - 选择总和忽略分组依据

PHP - 将关联数组输出到 HTML <divs with labels/headings

javascript - 错误 JSON.parse : unexpected end of data at line 1 column 1 of the JSON data

php - 在 Ubuntu 16.10 上将 PHP 从 5.6 降级到 5.5

MySQL 使用 if 语句从多个表中进行 SELECT