2011-04-19 140 views
2

基本上我不想在某些字段中出現重複的數字。我怎麼做?php檢查數據庫中是否存在數字

table user: 
id name group 
1 a  2 
2 b  3 
3 c  1 
4 d  6 
5 e  5 

$q = $db->query("SELECT COUNT(t_group) FROM user"); 
$r = $q->fetch_row; 
if($r[0] > 0) : 
    $rand_no = rand(1,10); 
    $db->query("INSERT INTO user(name, group) VALUES('$name','$rand_no')"); 
endif; 
+0

你能否闡述只是稍微它是什麼,你要完成?你爲什麼使用rand()?它永遠不會保證你不會得到重複(遠離它)。 – 2011-04-19 15:41:56

+4

爲什麼不在數據庫中使該字段獨一無二? – eaj 2011-04-19 15:42:10

+0

我同意重新:通過數據庫獨特的執法。如果它對於數據完整性非常重要,不要依賴您的代碼。特別是如果您不使用類或庫來處理所有數據庫接口,那麼您需要記住在每次更新表的每一處執行它。 – horatio 2011-04-19 15:53:22

回答

3

使用insert ... where not exists

示例代碼

//prevent those pesky SQL injection attacks 
$rand_no = mysql_real_escape_string($rand_no); 
$name = mysql_real_escape_string($name); 

//Only insert if group is not already used 
$db->query("insert into user(name, `group`) 
      VALUES('$name',$rand_no) 
      where not exists 
       (select `group` from user where `group` = '$rand_no'))"; 

我已經添加了前兩行沒有提醒你忘記逃避這些值來防止SQL注入攻擊。 (如果是由PHP代碼生成$rand_no,就沒有必要逃避,當然,但如果用戶可以操縱它,那麼你應該)

其次group是保留字,如果你想用它您需要將查詢括在反引號'`中。

編輯:
強制在數據庫
設置字段group是採用了獨特的場ALTER TABLE

ALTER TABLE CHANGE COLUMN `group` `group` UNIQUE 
+0

您需要添加$ group = rand(1,10); – Wil 2011-04-19 15:45:01

+0

如果該組已經存在,是否不會對此陳述採取任何行動?這不會提示php沒有任何事情。我錯了嗎? – Dutchie432 2011-04-19 15:45:42

+0

@Johan:謝謝! $ group從哪裏來? – tonoslfx 2011-04-19 15:49:32

0

你想生成一個隨機數,然後看看在該領域已經有了這個數字的記錄。比方說,你的隨機數是8

select top 1 group from user where group=8 

如果任何行返回,數量不是唯一的。

1

PHP

var stop_cycle = 0; 

while (!stop_cycle) { 

$rand_no = rand(1,10); 
$db->query("SELECT group FROM user WHERE group = ".$rand_no); 

// check if query returns any result 
if(mysql_affected_rows() == 0) { 

// value is unique, let's insert it 
$db->query("INSERT INTO user(name, group) VALUES('$name','$rand_no')"); 

// end cycle 
stop_cycle=1; 
} 

} 
相關問題