通过我的网站,我会在很多不同的设置中显示不同的产品,以确保结果的数量是正确的,我想用PHP回应它们。到目前为止,我已经尝试按照我所知道的方式回应它们,但这种做法并没有奏效。
我要回显的页面上的代码包含顶部的函数文件的require。我试过了:
<?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;
}
答案 0 :(得分:0)
将您的功能更改为:
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'];
}
答案 1 :(得分:0)
从
改变//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;
}
到
//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(*) as total_result FROM stock';
//use a prepared statement to enhance security
$statement = $conn->prepare($sql);
$statement->execute();
$result = $statement->get_result();
$row = $result->fetch_assoc();
$statement->closeCursor();
return $row['total_result'];
}
也从
改变<?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>
到
<?php
//Call the count_stock() function
$result_count = count_stock();
?>
<p>Showing 1-9 of <?php echo $result_count; ?> results.</p>
答案 2 :(得分:0)
试试这个
$sql = "SELECT count(*) FROM `stock";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
上面的代码示例使用了一个预准备语句,在许多情况下,为了计算行数,这可能是不必要的,所以:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
参考:http://php.net/manual/en/pdostatement.rowcount.php
注意: PDO有PDOStatement :: rowCount(),显然在MySql中不起作用。多么痛苦