From 34c0172c5f1f5a152cd2d5ced0cab6d528ea5746 Mon Sep 17 00:00:00 2001 From: foxycode Date: Sun, 28 Jun 2015 13:56:15 +0200 Subject: [PATCH] Selection: added fetchField() --- src/Database/Table/Selection.php | 20 ++++++++++++++++ .../Table/Selection.fetchField().phpt | 24 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 tests/Database/Table/Selection.fetchField().phpt diff --git a/src/Database/Table/Selection.php b/src/Database/Table/Selection.php index cce1a63df..296b3c97e 100644 --- a/src/Database/Table/Selection.php +++ b/src/Database/Table/Selection.php @@ -223,6 +223,26 @@ public function fetch() } + /** + * Fetches single field. + * @param string|NULL + * @return mixed|FALSE + */ + public function fetchField($column = NULL) + { + if ($column) { + $this->select($column); + } + + $row = $this->fetch(); + if ($row) { + return $column ? $row[$column] : array_values($row->toArray())[0]; + } + + return FALSE; + } + + /** * @inheritDoc */ diff --git a/tests/Database/Table/Selection.fetchField().phpt b/tests/Database/Table/Selection.fetchField().phpt new file mode 100644 index 000000000..9a54a10b2 --- /dev/null +++ b/tests/Database/Table/Selection.fetchField().phpt @@ -0,0 +1,24 @@ +table('book')->where('id', 1)->fetchField('title'); // SELECT `title` FROM `book` WHERE `id` = 1 + Assert::same('1001 tipu a triku pro PHP', $title); +}); + + +test(function () use ($context) { + $title = $context->table('book')->where('id', 1)->select('title')->fetchField(); // SELECT `title` FROM `book` WHERE `id` = 1 + Assert::same('1001 tipu a triku pro PHP', $title); +});