简体   繁体   English

无法删除CodeIgniter中数据库中最旧的记录

[英]Can't delete the oldest record in database in CodeIgniter

I made a website using CodeIgniter framework. 我使用CodeIgniter框架制作了一个网站。 I have a user system and I am trying to keep in my database only the last 5 logins. 我有一个用户系统,我试图仅将最近5次登录保留在我的数据库中。 Here is the code I have written: 这是我编写的代码:

$logins = array(
   'uid'  => $user['id'],
   'time' => now(),
   'ip'   => $this->input->ip_address()
);
$this->db->insert('logins', $logins);
$this->db->where('uid', $user['id']);
$logins_no = $this->db->count_all_results('logins');
$logins_deleted = $logins_no - 5;
if ($logins_deleted > 0) {
    $this->db->where('uid', $user['id']);
    $this->db->order_by('time asc');
    $this->db->limit($logins_deleted);
    $this->db->delete('logins');
}

So basically, I am inserting the date and IP when a user is connecting then I count all the records of the user in the logins table from the database. 因此,基本上,我在用户连接时插入日期和IP,然后在数据库的登录表中计算该用户的所有记录。 If there are more than 5 logins I count how many results I have to delete. 如果登录数超过5,我计算必须删除多少结果。

Why it isn't working? 为什么不起作用?

SQL doesn't allow for an ORDER BY clause to be part of a DELETE query so you'll have to do as Jeemusu suggested: SQL不允许ORDER BY子句成为DELETE查询的一部分,因此您必须按照Jeemusu的建议进行操作:

Get an unique identifier of the rows you intend to delete. 获取要删除的行的唯一标识符。 You haven't specified whether or not you have a primary column (you should) so we'll just go with the time column for the sake of the explanation: 您尚未指定是否有主列(应该),因此为了说明起见,我们将仅使用时间列:

$query = $this->db->where('uid', $user['id'])->order_by('time asc')->limit(5)->get('logins');
$result = $query->result();

Create an array with the values of the time columns: 使用时间列的值创建一个数组:

$times = array();
foreach($result as $r) {
    $times[] = $r->time;
}

Now use the where_in method of Active Record to delete these rows: 现在,使用Active Record的where_in方法删除以下行:

$this->db->where_in('time', $times)->where('uid', $user['id'])->delete('logins');

You can disregard the second where method used if you go for deleting based on the primary key. 如果您要基于主键进行删除,则可以忽略第二个where方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM