我正在使用 PHP 8.2 中新的 mysqli::execute_query 并希望获取客户下的订单总数以及订单数组。
简化代码:
$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);
可以只用一个execute_query来完成吗?
当我们有数据时,我们总是可以得到没有 num_rows 的计数:
$sql = "select * from orders WHERE userid= ? ORDER BY orderid DESC";
$orderdata = $MySQLi->execute_query($sql, [$userid])->fetch_all(MYSQLI_ASSOC);
$ordercount = count($orderdata);
如果仅选择一条记录,则可以将获取的行用作计数值(或者更确切地说,用作告诉是否找到记录的标志),即
$sql = "select * from users WHERE id=?";
$user = $MySQLi->execute_query($sql, [$userid])->fetch_assoc();
if ($user) { ...