【问题标题】:Code only updates false value in DB, but not true代码仅更新 DB 中的 false 值,但不更新 true
【发布时间】:2016-08-06 10:46:59
【问题描述】:

我有一个奇怪的情况,只有错误的状态被保存到数据库中。当“状态”应该为真时,我的查询仍然执行为假。

我有这个功能的控制器

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;
}

【问题讨论】:

  • 你的数据库中活动字段的数据类型是什么?在 mysql 控制台中运行错误查询会发生什么?
  • 确保您的数据库名称设置为$tablename = $this->table;
  • 附加检查可以缩短为$state['active'] = ($this->input->post('state') == 'true');
  • 哇。好的!再次感谢您

标签: php mysql codeigniter codeigniter-3


【解决方案1】:

这里 'true' 被引用,因此它被作为字符串插入:

MY_model.php:46:string 'UPDATE `Locations` SET `active` = 'true'

在 MySQL 中,两个字符串 'true''false' 在放入 tinyint(1) 列时都会转换为 0,因为两者都不是正确的数值。

使用值 01 将起作用。 MySQL 还定义了常量 FALSE (0) 和 TRUE (1),因此只要您将它们插入不带引号而不是字符串形式,它们也将起作用。

【讨论】:

  • 我正在使用 mysql。好的将运行一些测试,将字符串转换为“真,假”,但据我所知,这应该自动完成
  • 是的!我已经用我的解决方案更新了这个问题。我必须进行一些额外的检查才能插入“真,假”。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多