Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

php - PDO returns false instead of empty array

I am using PHP 7.4 and my class have a function that should return an array. But if the row is empty it returns false instead of an empty array. That is why I get an error message:

Return value must be of type array, bool returned

private function getCartItem(int $sku): array
{
    $statement = $this->pdo->prepare("SELECT * FROM pbo_cartItem WHERE cartId = ? AND sku = ?");
    $statement->execute(array($this->cartId, $sku));
    return $statement->fetch(PDO::FETCH_ASSOC);
}
question from:https://stackoverflow.com/questions/65852300/pdo-returns-false-instead-of-empty-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The PDOStatement::fetch() method returns false if there are no more rows in the result set.

To overcome this error message, provide an empty array as a default value in case no rows were found.

return $statement->fetch(PDO::FETCH_ASSOC) ?: [];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...