diff --git a/flight/database/PdoWrapper.php b/flight/database/PdoWrapper.php index 6f37b25..4c036cd 100644 --- a/flight/database/PdoWrapper.php +++ b/flight/database/PdoWrapper.php @@ -91,11 +91,14 @@ class PdoWrapper extends PDO * @param string $sql - Ex: "SELECT id FROM table WHERE something = ?" * @param array $params - Ex: [ $something ] * - * @return mixed + * @return mixed|false */ public function fetchField(string $sql, array $params = []) { $result = $this->fetchRow($sql, $params); + if ($result === null || count($result) === 0) { + return false; + } $data = $result->getData(); return reset($data); } diff --git a/tests/PdoWrapperTest.php b/tests/PdoWrapperTest.php index d7e9311..904d95c 100644 --- a/tests/PdoWrapperTest.php +++ b/tests/PdoWrapperTest.php @@ -71,6 +71,12 @@ class PdoWrapperTest extends TestCase $this->assertEquals(2, $id); } + public function testFetchFieldReturnsFalseWhenNoResults(): void + { + $id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE id = ?', [999]); + $this->assertFalse($id); + } + public function testFetchRow(): void { $row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']); diff --git a/tests/SimplePdoTest.php b/tests/SimplePdoTest.php index 08f8e16..ee41697 100644 --- a/tests/SimplePdoTest.php +++ b/tests/SimplePdoTest.php @@ -468,4 +468,10 @@ class SimplePdoTest extends TestCase $id = $this->db->fetchField('SELECT id, name FROM users WHERE id = ?', [1]); $this->assertEquals(1, $id); } + + public function testFetchFieldReturnsFalseWhenNoResults(): void + { + $value = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [999]); + $this->assertFalse($value); + } }