Commit 2bfb6ca2 authored by Alexander Butenko's avatar Alexander Butenko

added rawQueryOne rawQueryValue()

parent fa54e4d6
......@@ -326,6 +326,49 @@ class MysqliDb
return $res;
}
/**
* Helper function to execute raw SQL query and return only 1 row of results.
* Note that function do not add 'limit 1' to the query by itself
* Same idea as getOne()
*
* @param string $query User-provided query to execute.
* @param array $bindParams Variables array to bind to the SQL statement.
*
* @return array Contains the returned row from the query.
*/
public function rawQueryOne ($query, $bindParams = null) {
$res = $this->rawQuery ($query, $bindParams);
if (is_array ($res) && isset ($res[0]))
return $res[0];
return null;
}
/**
* Helper function to execute raw SQL query and return only 1 column of results.
* If 'limit 1' will be found, then string will be returned instead of array
* Same idea as getValue()
*
* @param string $query User-provided query to execute.
* @param array $bindParams Variables array to bind to the SQL statement.
*
* @return mixed Contains the returned rows from the query.
*/
public function rawQueryValue ($query, $bindParams = null) {
$res = $this->rawQuery ($query, $bindParams);
if (!$res)
return null;
$limit = preg_match ('/limit\s+1;?$/i', $query);
$key = key ($res[0]);
if (isset($res[0][$key]) && $limit == true)
return $res[0][$key];
$newRes = Array ();
for ($i = 0; $i < $this->count; $i++)
$newRes[] = $res[$i][$key];
return $newRes;
}
/**
*
* @param string $query Contains a user-provided select query.
......
......@@ -219,6 +219,28 @@ foreach ($users as $user) {
print_r ($user);
}
```
To avoid long if checks there are couple helper functions to work with raw query select results:
Get 1 row of results:
```php
$user = $db->rawQueryOne ('select * from users where id=?', Array(10));
echo $user['login'];
// Object return type
$user = $db->ObjectBuilder()->rawQueryOne ('select * from users where id=?', Array(10));
echo $user->login;
```
Get 1 column value as a string:
```php
$password = $db->rawQueryValue ('select password from users where id=? limit 1', Array(10));
echo "Password is {$password}";
NOTE: for a rawQueryValue() to return string instead of an array 'limit 1' should be added to the end of the query.
```
Get 1 column value from multiple rows:
```php
$logins = $db->rawQueryValue ('select login from users limit 10');
foreach ($logins as $login)
echo $login;
```
More advanced examples:
```php
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment