当我的用户登录活动的模型时。如果用户在更新属于用户标识的行之前已登录。否则应该插入行。
问题:目前它只是更新与之前相同的行。如果用户ID之前没有登录,它应该插入一个新行。
如何修复模型上的问题。
<?php
class Model_account_activity extends CI_Model {
public function updateActivity($key, $data) {
$data['user_id'] = $this->session->userdata('user_id');
if (isset($data['user_id'])) {
$user_id = $data['user_id'];
} else {
$user_id = 0;
}
$query = $this->db->query("UPDATE `" . $this->db->dbprefix . "user_activity` SET
`user_id` = '" . (int)$user_id . "',
`key` = " . $this->db->escape($key) . ",
`data` = " . $this->db->escape(serialize($data)) . ",
`date_added` = NOW()
");
if ($query == FALSE) {
$this->addActivity();
return true;
} else {
return false;
}
}
public function addActivity($key, $data) {
$data['user_id'] = $this->session->userdata('user_id');
if (isset($data['user_id'])) {
$user_id = $data['user_id'];
} else {
$user_id = 0;
}
$this->db->query("INSERT INTO `" . $this->db->dbprefix . "user_activity` SET
`user_id` = '" . (int)$user_id . "',
`key` = " . $this->db->escape($key) . ",
`data` = " . $this->db->escape(serialize($data)) . ",
`date_added` = NOW()
");
}
}
答案 0 :(得分:0)
通过唯一DB
或ID
从primary key
获取结果,然后检查查询结果。如果结果计数为0
,则可以插入其他更新。实施例...
$this->db->where('column_name', $user_id); //Unique column or primary_key .It may be $user_id
$query = $this->db->get('table_name');
if($query->num_rows == 0)
{
//Insert query
}
else
{
//Update query
}
答案 1 :(得分:0)
感谢@Please Wait
现在所有工作,我的工作原理如何。
<?php
class Model_account_activity extends CI_Model {
public function activity($key, $data) {
$user_id = $this->session->userdata('user_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get('user_activity');
$data['user_id'] = $this->session->userdata('user_id');
if (isset($data['user_id'])) {
$user_id = $data['user_id'];
} else {
$user_id = 0;
}
if($query->num_rows() == FALSE) {
$data = array(
'user_id' => $user_id,
'key' => $key,
'data' => serialize($data),
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert_id();
$this->db->insert('user_activity', $data);
} else {
$data = array(
'user_id' => $user_id,
'key' => $key,
'data' => serialize($data),
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->where('user_id', $user_id);
$this->db->update('user_activity', $data);
}
}
}