I’m using the new mysqli::execute_query in PHP 8.2 and want to get the total number of orders placed by a customer and an array of the orders.
Simplified code:
$MySQLi = new mysqli( "host", "username", "password", "database");
$sql = "select * from orders WHERE userid = ? ";
$ordercount = $MySQLi->execute_query($sql, [$userid])->num_rows;
$orderdata = $MySQLi->execute_query($sql, [$userid])->fetch_all(MYSQLI_ASSOC);
Can it be done with just a single execute_query ?
2
Answers
When we have the data, we can always have the count without num_rows:
In case only one record is selected, the fetched row can be used as a count value (or, rather, as a flag that tells whether a record was found or not), i.e.
There is a simple solution to this: don’t do it in one line. Just because
mysqli_execute_query()
lets you do things in one line doesn’t mean it’s a good idea.You can save the result in a variable, then access the
num_rows
property and fetch the rows, all on separate lines.However, the
num_rows
property is quite useless (the same goes for its function equivalent). It is exactly the same as getting the count of elements in the fetched array.So, if you want to do it in one line and get the count of rows, you can just use
count()
.