【问题标题】:Codeigniter model not saving on databaseCodeigniter 模型未保存在数据库中
【发布时间】:2016-06-23 21:57:19
【问题描述】:

我有一个应用程序应该将每笔交易都保存在我的数据库中。控制器代码如下:

$info = array(
    'student_id' => $this->user['id'],
    'transaction_id' => $ref,
    'value' => $amount,
    'final_value' => $final_value,
    'payment_status' => '0',
    'date' => date('Y-m-d'),
  );

$this->load->model('student_model');
if($this->student_model->insertPurchaseForStudent($info)){

  // Some other code here 

}

这是我的模型('student_model'):

public function insertPurchaseForStudent($info){
  if($this->db->insert('compra', $this->db->escape($info))){
    return true;
  }else{
    return false;
  }
}

我非常头疼,因为有些事务保存在数据库中,而另一些则没有。我认为这可能是我的数据库服务器上的某种不稳定因素,所以我添加了一个 for 循环,以便多次尝试,并在无法保存时记录错误消息:

$i = 1;
for ($i == 1; $i <= 5; $i++) {
  if($this->student_model->insertPurchaseForStudent($info)){

    // to leave the loop
    $i = 7;

    // Some other code here 

  }else{
    sleep(3);
    switch($i){
      case 2 :
        log_message('error', 'Second attempt to add transaction');
      break;
      case 3 :
        log_message('error', 'Third attempt to add transaction');
      break;
      case 4 :  
        log_message('error', 'Fourth attempt to add transaction');
      break;
      case 5 :
        log_message('error', 'Fifth attempt to add transaction');
      break;
      case 6 :
        log_message('error', 'Sixth attempt, giving up');
      break;
    }
  }
}

问题是,当它不保存事务时,我的错误日志上看不到任何消息。

我非常感谢任何关于可能原因的想法,或者我在我编写的这段代码中滑倒的地方。

干杯。

【问题讨论】:

  • 对不起@quantme,$info 是一个包含交易信息的数组。我已经更新了我的问题。谢谢!
  • $this-&gt;user['id'] 来自先前/当前的数据库操作还是来自会话?
  • 我试图复制错误,还没有。如果您仍然有问题,您必须提供更多信息(代码)。
  • @quantme,感谢您的帮助。 $this-&gt;user['id'] 来自一个会话:$this-&gt;data['user'] = $this-&gt;user = $this-&gt;session-&gt;userdata('user');
  • 你在会话中使用什么driver

标签: php mysql codeigniter activerecord


【解决方案1】:

首先,我要感谢所有帮助过我的人。

我终于找到了问题所在。很蹩脚,对不起。

模型和控制器都很好。他们将交易保存在我的数据库中。

但我有一个名称错误的函数“courseForStudentCheck()”,它不仅会检查学生是否已注册,还会将其从我的数据库中删除。在某些情况下我需要它,但我应该以不同的方式命名它,因为我无意中开始使用它只是为了检查用户是否已注册。这就是问题的根源。

再次感谢!

【讨论】:

    【解决方案2】:

    尝试像这样使用$this-&gt;db-&gt;set($data)

    public function insertPurchaseForStudent($info){
      $this->db->set($info);
      if($this->db->insert('compra'){
        return true;
      } else {
        return false;
      }
    }
    

    您可以在CodeIgniter Manual Inserting Data 中找到更多使用set() 的示例

    看看它是否有效。

    【讨论】:

    • 感谢@MSI,我正在部署此修复程序,如果再次发生,我会更新问题。
    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2021-06-28
    • 2015-11-13
    相关资源
    最近更新 更多