fix: return false from fetchField on empty result

SimplePdo::fetchRow() returns null when there are no rows. Guard
PdoWrapper::fetchField() so empty queries return false instead of
calling getData() on null. Closes #726.
pull/727/head
Ambrose Casanova 5 days ago
parent a406f917e8
commit e42c7848c4

@ -91,11 +91,14 @@ class PdoWrapper extends PDO
* @param string $sql - Ex: "SELECT id FROM table WHERE something = ?" * @param string $sql - Ex: "SELECT id FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ] * @param array<int|string,mixed> $params - Ex: [ $something ]
* *
* @return mixed * @return mixed|false
*/ */
public function fetchField(string $sql, array $params = []) public function fetchField(string $sql, array $params = [])
{ {
$result = $this->fetchRow($sql, $params); $result = $this->fetchRow($sql, $params);
if ($result === null || count($result) === 0) {
return false;
}
$data = $result->getData(); $data = $result->getData();
return reset($data); return reset($data);
} }

@ -71,6 +71,12 @@ class PdoWrapperTest extends TestCase
$this->assertEquals(2, $id); $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 public function testFetchRow(): void
{ {
$row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']); $row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']);

@ -468,4 +468,10 @@ class SimplePdoTest extends TestCase
$id = $this->db->fetchField('SELECT id, name FROM users WHERE id = ?', [1]); $id = $this->db->fetchField('SELECT id, name FROM users WHERE id = ?', [1]);
$this->assertEquals(1, $id); $this->assertEquals(1, $id);
} }
public function testFetchFieldReturnsFalseWhenNoResults(): void
{
$value = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [999]);
$this->assertFalse($value);
}
} }

Loading…
Cancel
Save