简体   繁体   English

在计算mysql表的总行数时是否可以避免使用“ AS”参数? (php)

[英]Is it possible to avoid the “AS” parameter when counting total rows of a mysql table? (php)

Now I use this code to count the total rows of a table: 现在,我使用以下代码来计算表的总行数:

$sql = "SELECT COUNT(*) AS Total FROM MyTable";
$result = mysqli->query($sql);
$numberOfRows = mysqli_fetch_object($result);
$numberOfRows = $numberOfRows->Total;

I've tried to dump different results that I get when I don't use the "AS" parameter in the query and searched around in the internet about it, but despite the many examples I've found none of them shows the code to retrieve directly the result without the "AS" paramenter. 我尝试转储当我在查询中不使用“ AS”参数并在互联网上进行搜索时得到的不同结果,但是尽管有很多示例,但我发现它们都没有显示代码不使用“ AS”参数直接检索结果。

... ...

From the answers and comments received I've tried these two code blocks that give the expected result: 从收到的答案和评论中,我尝试了这两个提供预期结果的代码块:

$sql = "SELECT COUNT(*) FROM MyTable";
$result = mysqli->query($sql);

And then: With fetch array: 然后:使用获取数组:

$numberOfRows = $result->fetch_array($result);
$numberOfRows = $numberOfRows[0];

With fetch assoc: 使用提取assoc:

$numberOfRows = $result->fetch_assoc($result);
$numberOfRows = $numberOfRows["COUNT(0)"];

Performance wise I've found the fetch array works slightly better (tried without opcode). 在性能方面,我发现访存数组的性能略好一些(尝试不使用操作码)。

If you don't use AS to assign an alias, the name of the column in the output will be COUNT(*) . 如果不使用AS分配别名,则输出中的列名称将为COUNT(*) You should then be able to retrieve it with: 然后,您应该可以使用以下方法检索它:

$numberOfRows = $numberOfRows->{"COUNT(*)"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM