我有一个函数可以从 MySQL 数据库中获取用户详细信息。 如果提供的函数参数是一个整数,函数将其视为用户 ID,如果参数是一个字符串,它将检查字符串是否是预定义数组中的键,如果参数是数组中的键,则将参数视为user_group id(从配置文件中获取),如果参数是字符串但不在数组键中,则它将参数视为用户名,如果不满足任何条件,则会抛出错误。
问题:如果我向函数提供用户名(字符串),它会正常工作。如果我提供一个字符串,它是预定义数组中的一个键,那么它就可以工作。
如果我提供用户 ID (int),它适用于除 1 之外的所有 ID。也就是说,如果 $param
是 1,它会给我“错误 3”(在代码下方),如果提供的整数是数据库中的任何其他 id,那么它就可以工作。
ID 1 确实存在于数据库中。奇怪的是,即使提供的 id 为 1,var_dump() 实际上也会转储正确的数据。
这是最后一个查询字符串:SELECT * FROM user
as u
JOIN user_details
as ud
ON u
.id
= ud
.id_user
WHERE u
.用户名
= '1'
很明显,它将 1 视为字符串而不是整数。 为什么? 为什么它仍然获取第一条记录 (id=1),尽管它将 id 视为用户名 u
。username
= ' 1'?
如果我在 function _initialize ( $param )
的开头添加 $param = 1;
,则会出现以下错误。
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 49 bytes) in E:\APACHE\htdocs\codeigniter\lib\system\database\DB_query_builder.php on line 2677
protected function _initialize ( $param )
{
$this->ci->db->select ( '*' );
$this->ci->db->from ( $this->tableUser [ 'table' ] . ' as u' );
$compare = NULL;
if ( is_int ( $param ) ){
$compare = $this->tableUser [ 'column' ] [ 'id' ];
}
elseif ( is_string ( $param ) && array_key_exists ( $param, $this->constantsServices ) ){
$compare = $this->tableUser [ 'column' ] [ 'id_user_groups' ];
$param = $this->constantsServices [ $param ];
}
else if ( is_string ( $param ) ){
$compare = $this->tableUser [ 'column' ] [ 'username' ];
}else {
throw new Exception ( 'Error 1' );
}
$this->ci->db->where ( 'u.' . $compare, $param );
$this->ci->db->join ( $this->tableUserDetails [ 'table' ] . ' as ud', 'u.' . $this->tableUser [ 'column' ] [ 'id' ] . ' = ud.' . $this->tableUserDetails [ 'column' ] [ 'id_user' ] );
$query = $this->ci->db->get ( );
if ( ! $query ){
throw new Exception ( 'Error 2' );
}
$data = $query->unbuffered_row('array');
var_dump ( $data );
if ( !isset ( $data ) ){
throw new Exception ( 'Error 3' );
}
}
最佳答案
您应该使用正则表达式来找出数字/数字值。
而不是 is_int
使用
if(preg_match('/^\d+$/',$param))
{
//Your code goes here
// Then typecast your parameter as
$param = (int)$param
}
关于php - 奇怪的 PHP 和 Codeigniter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213287/