Skip to content

Commit b16bc91

Browse files
authored
Merge pull request #1 from thingNumber1/patch-1
Add validation function `in_db`
2 parents e3e617c + db13446 commit b16bc91

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

system/Validation/Rules.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,47 @@ public function greater_than_equal_to(string $str = null, string $min, array $da
139139

140140
//--------------------------------------------------------------------
141141

142+
/**
143+
* Checks the database to see if the given value exist.
144+
* Can ignore records by field/value to filter (currently
145+
* accept only one filter).
146+
*
147+
* Example:
148+
* in_db[table.field,where_field,where_value]
149+
* in_db[menu.id,active,1]
150+
*
151+
* @param string $str
152+
* @param string $field
153+
* @param array $data
154+
*
155+
* @return boolean
156+
*/
157+
public function in_db(string $str = null, string $field, array $data): bool
158+
{
159+
// Grab any data for exclusion of a single row.
160+
list($field, $where_field, $where_value) = array_pad(explode(',', $field), 3, null);
161+
162+
// Break the table and field apart
163+
sscanf($field, '%[^.].%[^.]', $table, $field);
164+
165+
$db = Database::connect($data['DBGroup'] ?? null);
166+
167+
$row = $db->table($table)
168+
->select('1')
169+
->where($field, $str)
170+
->limit(1);
171+
172+
if (! empty($where_field) && ! empty($where_value))
173+
{
174+
$row = $row->where($where_field, $where_value);
175+
}
176+
177+
return (bool) ($row->get()
178+
->getRow() !== null);
179+
}
180+
181+
//--------------------------------------------------------------------
182+
142183
/**
143184
* Value should be within an array of values
144185
*

0 commit comments

Comments
 (0)