以下 codeigniter 函数采用(字符串)参数并返回行的(整数)ID。如果我传递字符串值,它工作正常,但如果传递整数 0,它会返回数据库中第一行的 ID。原则上,仅当数据库中存在 user_name
时,它才应返回 user_id
。由于没有名为 0 的 user_name,因此它应该返回 false。
有人能说出为什么会出现这样的情况以及如何修复它吗?
谢谢。
public function get_user_id($user_name)
{
$this -> db -> select('user_id');
$this -> db -> from('users');
$this -> db -> where('user_name', $user_name);
$this -> db -> limit(1);
$query = $this->db->get();
if ( $query->num_rows > 0 )
{
$row = $query->row();
return $row->user_id;
}
return false;
}
例如:
$user_name = "test"; //works fine, returns id.
$user_name = "0"; //works fine, doesnt return anything
$user_name = 0; //Problem. returns ID of first row.
最佳答案
您应该添加一个类似 if ($user_name == "") return false;
的测试来捕获此问题。
显然 where
与第二个参数 0 总是匹配,例如转换为 SQL WHERE user_name
,而不是 WHERE user_name = ""
,并且 WHERE user_name
是 WHERE user_name != 的简写形式""
——与你想要的相反:-)
当您传递的参数必然导致 false
时,在开始时运行此测试可以节省完整的数据库查询。
关于php - 关于PHP函数返回值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6439052/