Will this PHP isUnique function work?
It has been a while since I have programmed PHP so I am very rusty, so I just want to double check my work. With the following code work as a way to check if the string is unique against a database?
function isUnique($string, $type) {
switch ($type) {
case 'username':
$query = $this->db->select('username')
->from('olm_user')
->where('username', $string);
if (!$query->num_rows()) {
return false; // returns false if not taken?
}
break;
case 'email':
$query = $this->db->select('email')
->from('olm_user')
->where('email', $string);
if (!$query->num_rows()) {
return false; // returns false if not taken?
开发者_如何学运维 }
break;
case 'olname':
$query = $this->db->select('olname')
->from('olm_user')
->where('olname', $string);
if (!$query->num_rows()) {
return false; // returns false if not taken?
}
break;
}
}
If that's all you need to do (i.e. always query the olm_user
table, and type
always maps to the column name), maybe this would suffice:
<?php
function isUnique($string, $type) {
$query = $this->db->select($type)
->from('olm_user')
->where($type, $string);
return !$query->num_rows();
}
精彩评论