好的,我有这个最近的访问表和下面的代码我用来向用户明智地输入记录
if($user->is_logged_in() ){
$postid = $row['postid'];
$uid = $_SESSION['memberid'];
$stmt = "SELECT * FROM recent WHERE postid = :postid AND memberid = :memberid";
$stmt = $db->prepare($stmt);
$stmt->bindParam(':postid', $postid, PDO::PARAM_STR);
$stmt->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt->execute();
$recentCount = $stmt->rowCount();
if(!$recentCount)){
$stmt = $db->prepare('INSERT INTO recent (postid,memberid) VALUES ( :postid,:memberid)');
$stmt->execute(array(
':postid' => $postid,
':memberid' => $uid
));
}
}
但事情是我希望限制记录,因为在每个用户中只有50条记录应该在db中。假设用户访问了一个新主题,那么如果用户最近的表中已有50条记录,那么数字50将被删除,49条记录将变为50.我希望你明白我的观点?
只是每个用户的记录不应超过50是我的意思。
答案 0 :(得分:0)
根据问题和评论,我认为你可以这样做(你没有提到你的日期字段的名称,但是对于这个例子,我假设它被称为createddate) :
if($user->is_logged_in() ){
$postid = $row['postid'];
$uid = $_SESSION['memberid'];
$stmt = "SELECT COUNT(*) FROM recent WHERE postid = :postid AND memberid = :memberid"; //let mysql count the rows
$stmt = $db->prepare($stmt);
$stmt->bindParam(':postid', $postid, PDO::PARAM_STR);
$stmt->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt->execute();
$recentCount = $stmt->fetchColumn(); //fetch first column in first row, this will be the count result
if($recentCount >= 50)
{
$stmt2 = $db->prepare('DELETE FROM recent WHERE createddate = (select min(createddate) where memberid = :memberid)');
$stmt2->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt2->execute();
}
$stmt = $db->prepare('INSERT INTO recent (postid,memberid) VALUES ( :postid,:memberid)');
$stmt->execute(array(
':postid' => $postid,
':memberid' => $uid
));
如果PDO语法错误,我很抱歉,我暂时没有使用它。我相信你自己能做到这一点。但重要的是PHP的结构" if"声明和"删除" SQL。