【问题标题】:check user exist mysql php检查用户是否存在mysql php
【发布时间】:2014-05-13 06:12:56
【问题描述】:

我有下表

uId | groupId
==============
1     12
3     66

如何编写 mySQL 语句来检查用户是否存在于组中?

我的尝试

SELECT FROM usertable(uId) WHERE usertable.uId = $uId

上述查询只检查用户是否存在,但不检查用户是否属于特定组。

【问题讨论】:

  • 我想我会从教程开始。

标签: php mysql sql mysqli


【解决方案1】:

只需将该条件附加到您的 where 子句中,例如:

SELECT uId
FROM usertable
WHERE usertable.uId = 1
AND groupId = 12

【讨论】:

    【解决方案2】:

    只需将groupId 参数添加到您的查询WHERE 子句。

    $userId = x; // some user id
    $groupId = y; // some group id
    
    $con; // your mysqli instance
    
    if (!$stmt = $con->prepare('SELECT 1 FROM usertable WHERE uId = ? AND groupId = ?')) {
        throw new Exception($con->error, $con->errno);
    }
    
    $stmt->bind_param('ii', $userId, $groupId);
    
    if (!$stmt->execute()) {
        throw new Exception($stmt->error, $stmt->errno);
    }
    if ($stmt->fetch()) {
        // user exists and is in group
    }
    

    【讨论】:

    • @user3522722 是的,这样更安全。您是否真的在抱怨总共有 9 行 mysqli 代码可以保护您的查询免受 SQL 注入并提供错误检查。
    【解决方案3】:
    $query = mysql_query("Select from usertable(uId) where usertable.uId = $uId and groupId=$gid");
    
    if(mysql_num_rows($query)!=0){
    echo "user exists!";
    }else
    {
    echo "user not exists!";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      相关资源
      最近更新 更多