我正在解析CSV文件以将记录添加到表中。这就是我的方式。
public function parse_csv($file) {
$this->load->library('CSVReader');
$csvData = $this->csvreader->parse_file($file);
foreach($csvData as $key => $row) {
$data_n[$key] = array(
'mf_date' => $row['mf_date'],
'mf_student_id' => $row['mf_student_id'],
'mf_sender' => $row['mf_sender'],
'mf_amount' => $row['mf_amount'],
'mf_trx_id' => $row['mf_trx_id'],
);
$this->db->insert('monthly_fee', $data_n[$key]);
$this->student_model->update_monthly_due($row['mf_student_id'], $row['mf_amount']);
}
}
我希望更新另一个有三列
的表格1)md_student_id //unique
2)md_due
3)md_paid
我想在上传csv时更新该表,其中mf_student_id和md_student_id与下面的模型函数匹配。
public function update_monthly_due($mf_student_id, $mf_amount)
{
$this->db->select('mf_student_id');
$this->db->from('monthly_fee');
$this->db->join('monthly_due', 'monthly_due.md_student_id = monthly_fee.mf_student_id');
$sql = "UPDATE monthly_due set md_due = md_due - " . $mf_amount . ", md_paid = md_paid + " . $mf_amount . " WHERE md_student_id = " . $mf_student_id;
$this->db->query($sql);
}
但是当我上传csv时会产生以下错误。
Error Number: 1054
Unknown column 'MCS20145B41' in 'where clause'
UPDATE monthly_due set md_due = md_due - 5500, md_paid = md_paid + 5500 WHERE md_student_id = MCS20145B41
Filename: F:\xampp\htdocs\student\system\database\DB_driver.php
Line Number: 330
我做错了什么?!
提前致谢
答案 0 :(得分:1)
您应该将此行替换为
$sql = "UPDATE monthly_due set md_due = md_due - " . $mf_amount . ", md_paid = md_paid + " . $mf_amount . " WHERE md_student_id = '" . $mf_student_id . "'";
注意这一行的结尾
答案 1 :(得分:1)
为什么不使用 CI的活动记录而不是原始SQL查询。
在执行此操作时,正确的方式。以下是:
更改此内容,
$sql = "UPDATE monthly_due set md_due = md_due - " . $mf_amount . ", md_paid = md_paid + " . $mf_amount . " WHERE md_student_id = " . $mf_student_id;
$this->db->query($sql);
要,强>
$this->db->where('md_student_id', $mf_student_id);
$this->db->set('md_due', "md_due - $mf_amount", FALSE);
$this->db->set('md_paid', "md_paid + $mf_amount", FALSE);
$this->db->update('monthly_due');
的说明:强>
这是有效的原因是因为第三个(可选)FALSE参数告诉CodeIgniter不用反引号保护生成的查询(')。这意味着生成的SQL将是:
UPDATE monthly_due set md_due = md_due - 5500, md_paid = md_paid + 5500 WHERE md_student_id = "MCS20145B41"