代码只更新数据库中的 false 值,而不是 true
Code only updates false value in DB, but not true
我有一个奇怪的情况,只有错误的状态被保存到数据库中。当 "state" 应该为 true 时,我的查询仍然执行 false。
我有带此功能的控制器
public function change_active_state_post()
{
$id['id_location'] = $this->input->post('id_location');
$state['active'] = $this->input->post('state');
var_dump($state['active']);
$this->locations->update($state, $id);
}
这是MY_Model更新函数
function update($data,$conditions,$tablename=""){
if($tablename=="")
$tablename = $this->table;
$this->db->where($conditions);
$this->db->update($tablename,$data);
var_dump($this->db->last_query());
return $this->db->affected_rows();
}
当我请求停用位置时,我在日志中得到以下数据,并且数据库已正确更新
Location.php:196:string 'false' (length=5)
MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'false'
WHERE `id_location` = '2'' (length=67)
但是当我请求激活位置时,我在我的日志中得到了以下数据,并且数据库值没有更新
Location.php:196:string 'true' (length=4)
MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'true'
WHERE `id_location` = '2'' (length=66)
问题是活动列永远不会更新为值 1 或 true。它保持为 0,但如果我不想将其从 1 变为 0,它将始终有效。
数据库中的活动列类型是 tinyint(1)
如果您需要任何其他信息,请告诉我,我会提供:提前致谢
更新
这个额外的检查帮助我正确地插入数据
if($this->input->post('state') == 'true'){
$state['active'] = true;
}else{
$state['active'] = false;
}
此处 'true'
被引用,因此它被作为字符串插入:
MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'true'
在 MySQL 中,两个字符串 'true'
和 'false'
在放入 tinyint(1)
列时都被转换为 0
,因为它们都不是正确的数值。
使用值 0
和 1
即可。 MySQL 还定义了常量 FALSE
(0
) 和 TRUE
(1
),因此只要您不加引号而不是将它们作为字符串插入,它们也可以工作.
我有一个奇怪的情况,只有错误的状态被保存到数据库中。当 "state" 应该为 true 时,我的查询仍然执行 false。
我有带此功能的控制器
public function change_active_state_post()
{
$id['id_location'] = $this->input->post('id_location');
$state['active'] = $this->input->post('state');
var_dump($state['active']);
$this->locations->update($state, $id);
}
这是MY_Model更新函数
function update($data,$conditions,$tablename=""){
if($tablename=="")
$tablename = $this->table;
$this->db->where($conditions);
$this->db->update($tablename,$data);
var_dump($this->db->last_query());
return $this->db->affected_rows();
}
当我请求停用位置时,我在日志中得到以下数据,并且数据库已正确更新
Location.php:196:string 'false' (length=5)
MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'false'
WHERE `id_location` = '2'' (length=67)
但是当我请求激活位置时,我在我的日志中得到了以下数据,并且数据库值没有更新
Location.php:196:string 'true' (length=4)
MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'true'
WHERE `id_location` = '2'' (length=66)
问题是活动列永远不会更新为值 1 或 true。它保持为 0,但如果我不想将其从 1 变为 0,它将始终有效。
数据库中的活动列类型是 tinyint(1)
如果您需要任何其他信息,请告诉我,我会提供:提前致谢
更新
这个额外的检查帮助我正确地插入数据
if($this->input->post('state') == 'true'){
$state['active'] = true;
}else{
$state['active'] = false;
}
此处 'true'
被引用,因此它被作为字符串插入:
MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'true'
在 MySQL 中,两个字符串 'true'
和 'false'
在放入 tinyint(1)
列时都被转换为 0
,因为它们都不是正确的数值。
使用值 0
和 1
即可。 MySQL 还定义了常量 FALSE
(0
) 和 TRUE
(1
),因此只要您不加引号而不是将它们作为字符串插入,它们也可以工作.