开发者

php check if number exists in database

basically i dont want duplicate number in certain field. how do i do that?

table user:
id 开发者_StackOverflow  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;


Use insert ... where not exists

Example code

//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') )";

I've added the first two lines to remind you no to forget to escape those values to prevent SQL-injection attacks. (if $rand_no is generated by the php code, there's no need to escape it of course, but if a user can manipulate it then you should)

Secondly group is a reserved word, if you want to use it in a query you need to bracket it in backquotes ' ` '.

EDIT:
Enforce it in the database
Set the field group to be a unique field using ALTER TABLE

ALTER TABLE CHANGE COLUMN `group` `group` UNIQUE


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;
}

}


You'll want to generate a random number and then see if there is already a record with that number in the field. Lets say your random number is 8

select top 1 group from user where group=8

If any rows return, the number is not unique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜