-1

The code below causes this warning:

Warning: count(): Parameter must be an array or an object that implements Countable

Why does it do that? How can I prevent the warning?

if (isset($_GET['edit'])) {
    $sonum = $_GET['edit'];
    $update = true;
    $result = $mysqli->query("SELECT * FROM salesorder WHERE sonum=$sonum") or die ($mysqli->error);

    if (count($result)==1) {
        $row = $result->fetch_array();
        $salesperson = $row['salesperson'];
        $company = $row['company'];
        $status = $row['status'];
    }
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
John Jeong
  • 13
  • 1

1 Answers1

2

$result will either be a mysqli_result object or bool. (See "Return Values" in the mysqli_query documentation.) Neither of those are countable. Newer PHP versions warn you when you try to count a non-countable thing, even though count() will still return a value (for now!)

That if (count($result)==1) { wouldn't have given that warning in PHP versions < 7.2, but it never really did anything, because count($result) would always be 1 whether the query failed or not. You might not expect it to be so, but count(false) returns 1. That's part of the reason it's a good thing that count() gives that warning now.

If you're just trying to set those variables if the query returned any rows, you can do it like this:

if ($result && $row = $result->fetch_array()) {
    $salesperson = $row['salesperson'];
    $company = $row['company'];
    $status = $row['status'];
}

By the way, you should take a look at How can I prevent SQL injection in PHP? and fix the injection vulnerability at ...WHERE sonum=$sonum". You should use a prepared statement and bind $sonum rather than including it in the SQL string.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Don't Panic
  • 41,125
  • 10
  • 61
  • 80