如何显示用户的排名?

时间:2017-07-09 19:15:53

标签: php sql pdo

我正在建立一个小排名系统,最终允许某些用户访问我网站的某些部分。我正在连接到我的数据库并选择包含我正在寻找的数据的正确表格/列,但由于某种原因它是空的?

这是我到目前为止的代码:

include "dbconf.php"; 
try {
    $conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
    //Trying to set PDO error mode to exception I guess?
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //No Need to say if we connected successfully. // echo "Connected Successfully!";
    $stmt = $conn->prepare("SELECT rank FROM members"); 
    $stmt->execute();
    $result = $userrank;
}
catch(PDOException $e) {
    echo "Connection to database has failed: " . $e->getMessage();
}
function ShowRank() {
    echo 'Rank: ' . $userrank;
}

因此,当执行此代码时,我不会收到任何类型的错误。但我得到的是空$userrank。当我尝试在另一个页面上调用它时,它返回:

Rank:但没有别的。

1 个答案:

答案 0 :(得分:4)

include "dbconf.php"; 
try {
    $conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
    //Trying to set PDO error mode to exception I guess?
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //No Need to say if we connected successfully. // echo "Connected Successfully!";
    $result = $conn->query("SELECT rank FROM members");
    $userrank = $result->fetchAll(PDO::FETCH_OBJ);
}
catch(PDOException $e)
{
    echo "Connection to database has failed: " . $e->getMessage();
}
function ShowRank($user) {
    echo 'Rank: ' . $user[1]->rank;
}
ShowRank($userrank);