Peter
Peter

Reputation: 393

correct way to check if user is found in mysql table

The function should return the id of the found user or return false if not found.

Currently I am using bind result and fetch to check if a user is found in an mysql table:

public function getUserIDByName($UserName) { 
        $uid = "";
        $i=0;
        if($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")){
            $stmt->bind_param("s", $UserName);
            $stmt->execute();
            $stmt->bind_result($uid);
            while($stmt->fetch()){
                $i++;
            }
            $stmt->close();
        }
        if($i==0){
            return false;
        }else{
            return $uid;
        }       
    } 

This works, but I assume that there is a proper way to do this without a counter in the fetch loop. I can not use get_result as mysqlnd is not available.

Upvotes: 2

Views: 100

Answers (3)

Crecket
Crecket

Reputation: 718

EDIT: just realized you're using mysqli and not pdo. Ill leave this here if you want to use PDO in the feature I guess.

This is how I would do it. You could change rowcount() > 0 to rowcount() === 1 if you want to guarantee only 1 user is found.

public function getUserIDByName($UserName)
{
    $stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name = :name");
    // bind :name to the username
    $stmt->bindParam(":name", $UserName); 
    // execute the query
    $stmt->execute(); 
    // check the rowcount
    if ($stmt->rowcount() > 0) { 
        // fetch the results as a associative array
        return $stmt->fetch(PDO::FETCH_ASSOC); 
    }
    // return false because rowcount wasn't bigger than 0
    return false;
}

Upvotes: 0

Saty
Saty

Reputation: 22532

Simple use num_rows to check your query return result or not

function getUserIDByName($UserName) {
    if ($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")) {
        $stmt->bind_param("s", $UserName);
        $stmt->execute();
        $row_cnt = $stmt->num_rows;
        if ($row_cnt == 1) {
            $stmt->bind_result($uid);
            while ($stmt->fetch()) {
                return $uid;
            }
        } else {
            return false;
        }
    }
}

Upvotes: 1

Kuldeep Dangi
Kuldeep Dangi

Reputation: 4422

Use this instead

public function getUserIDByName($UserName)
{
    $uid = '';
    $response = false;
    $stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?");
    $stmt->bind_param("s", $UserName);
    $stmt->execute();
    $stmt->bind_result($uid);
    if ($stmt->fetch()) {
        $response = $uid;
    }
    $stmt->close();
    return $response;
}

Upvotes: 0

Related Questions