skip to Main Content

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


  1. Chosen as BEST ANSWER

    When we have the data, we can always have the count without 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);
    

    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.

    $sql = "select * from users WHERE id=?";
    $user = $MySQLi->execute_query($sql, [$userid])->fetch_assoc();
    if ($user) { ...
    

  2. 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.

    $result = $MySQLi->execute_query($sql, [$userid]);
    $ordercount = $result->num_rows;
    $orderdata = $result->fetch_all(MYSQLI_ASSOC);
    

    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.

    $orderdata = $MySQLi->execute_query($sql, [$userid])->fetch_all(MYSQLI_ASSOC);
    $ordercount = count($orderdata);
    

    So, if you want to do it in one line and get the count of rows, you can just use count().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search