使用觸發器
實錄IP並將其存儲在留言簿表中。
然後創建一個觸發器,像這樣:
DELIMITER $$
CREATE TRIGGER bi_guestbook_each BEFORE INSERT ON guestbook FOR EACH ROW
BEGIN
DECLARE posts_today INTEGER;
SELECT COUNT(new.ip) INTO posts_today FROM guestbook
WHERE ip = new.ip AND postdate = new.postdate;
IF posts_today > 1 THEN BEGIN
//Force error by selecting from non-existing table
//this will prevent the insert from happening.
SELECT no_more_than_2_post_per_day_allowed
FROM before_insert_guestbook_error;
END; END IF;
END$$
DELIMITER ;
現在,你可以做刀片在你的PHP代碼擔心漲停。
觸發器將自動執行檢查。
使用INSERT ..選擇
如果你不想使用觸發器,使用INSERT ... SELECT語句。
首先確保場ip
在表定義定義爲NOT NULL
沒有默認值。
這會在嘗試將空值插入到留言簿表中時導致以下插入失敗。
<?php
$name = mysql_real_escape_string($_GET['name']);
$post = .....
$ip = ....
$query = "INSERT INTO guestbook (id, name, post_text, ip, postdate) SELECT
NULL AS id
, '$name' AS name
, '$post' AS post_text
, IF(guestbook.count(*)>=2,null,ip) AS ip
, CURDATE() AS postdate
FROM guestbook WHERE ip = '$ip' AND postdate = CURDATE()";
當然你也可以把IF(count(*) >= 2,null,...)
在被定義爲在表定義NOT NULL
任何列的地方。
鏈接:
選擇...插入:http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
觸發:http://dev.mysql.com/doc/refman/5.1/en/triggers.html
歡迎來到stackoverflow。 – Johan 2011-04-28 11:02:12
每天有兩篇文章「24小時內兩篇文章」或「兩篇文章在同一天」 - 意味着您可以在服務器時間23:59發佈兩條消息,然後在00:01發佈兩條消息嗎?下面的答案主要反映24小時內的帖子。 – cairnz 2011-04-28 11:37:08