简体   繁体   中英

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.

...

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:

$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(*) . You should then be able to retrieve it with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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