Page Menu
Home
DevCentral
Search
Configure Global Search
Log In
Files
F12576114
D3838.id.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
2 KB
Referenced Files
None
Subscribers
None
D3838.id.diff
View Options
diff --git a/database/src/Result/DatabaseResult.php b/database/src/Result/DatabaseResult.php
--- a/database/src/Result/DatabaseResult.php
+++ b/database/src/Result/DatabaseResult.php
@@ -19,4 +19,23 @@
* @return array|null An array if there is still a row to read; null if not.
*/
public abstract function fetchRow () : ?array;
+
+ /**
+ * Fetches the value from the first column of the first row in the result.
+ *
+ * This is typically used for queries that return a single scalar value
+ * such as SELECT count(*).
+ *
+ * @return mixed|null The value, or null if no more rows.
+ */
+ public function fetchScalar () : mixed {
+ $row = $this->fetchRow();
+
+ if (!$row) {
+ return null;
+ }
+
+ $key = array_key_first($row);
+ return $row[$key];
+ }
}
diff --git a/database/tests/Result/EmptyDatabaseResultTest.php b/database/tests/Result/EmptyDatabaseResultTest.php
--- a/database/tests/Result/EmptyDatabaseResultTest.php
+++ b/database/tests/Result/EmptyDatabaseResultTest.php
@@ -21,6 +21,10 @@
$this->assertEmpty($this->result->fetchRow());
}
+ public function testFetchScalar () : void {
+ $this->assertNull($this->result->fetchScalar());
+ }
+
public function testGetIterator () : void {
$actual = iterator_to_array($this->result->getIterator());
diff --git a/database/tests/Result/MockDatabaseResultTest.php b/database/tests/Result/MockDatabaseResultTest.php
--- a/database/tests/Result/MockDatabaseResultTest.php
+++ b/database/tests/Result/MockDatabaseResultTest.php
@@ -25,6 +25,10 @@
);
}
+ public function testFetchScalar () {
+ $this->assertEquals("strawberry", $this->result->fetchScalar());
+ }
+
public function testNumRows () {
$this->assertEquals(2, $this->result->numRows());
}
diff --git a/database/tests/Result/MySQLiDatabaseResultTest.php b/database/tests/Result/MySQLiDatabaseResultTest.php
--- a/database/tests/Result/MySQLiDatabaseResultTest.php
+++ b/database/tests/Result/MySQLiDatabaseResultTest.php
@@ -49,6 +49,10 @@
$this->assertEquals($expected, $this->result->fetchRow());
}
+ public function testFetchScalar () {
+ $this->assertEquals("1", $this->result->fetchScalar());
+ }
+
public function testNumRows () {
$this->assertEquals(4, $this->result->numRows());
}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Wed, Nov 12, 07:21 (12 h, 4 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3159016
Default Alt Text
D3838.id.diff (2 KB)
Attached To
Mode
D3838: Fetch a scalar value from a result
Attached
Detach File
Event Timeline
Log In to Comment