dongyuan2388 2011-04-19 15:38
浏览 80
已采纳

php检查数据库中是否存在数字

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

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;
  • 写回答

3条回答 默认 最新

  • dounao4179 2011-04-19 15:43
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写