-1

Here is my code, I am using my login system to display certain content to certain account levels. The problem is that for some reason my code is not working. As you can see below I am querying:

SELECT rank FROM members WHERE username='$authUser'

Which is supposed to get the rank of the user that is logged in Via:

$_SESSION['username']

PHP

<?php
include "dbconf.php"; 
include "loginheader.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!";
    $authUser = $_SESSION['username']; // get logged in user.
    $result = $conn->query("SELECT rank FROM members WHERE username='$authUser'");
    $userrank = $result->fetchAll(PDO::FETCH_OBJ);
}
catch(PDOException $e)
{
    echo "Connection to database has failed: " . $e->getMessage();
}

function ShowRank($user) {
    echo '<font color="green">' . $userrank[1] . '</font>';
}

?>

Now, where I am having trouble is that when I use:

var_dump($userrank);

What I get is an array that looks like this:

 array(1) { [0]=> object(stdClass)#4 (1) { ["rank"]=> string(13) "Administrator" } }

So naturally I wrote:

 echo $userrank[1];

However, for some reason it is returning empty. The output should be "Administrator" shouldn't it?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
DragonKyn
  • 69
  • 8
  • 4
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jul 10 '17 at 17:57
  • @JayBlanchard That still is coming up empty. – DragonKyn Jul 10 '17 at 18:02
  • I'd suggest putting some example code here (http://sandbox.onlinephpfunctions.com/) so people can help you a little bit better. – Brian Moreno Jul 10 '17 at 18:15
  • 1
    I just tested out `echo $userrank[0]['rank']` and it should work for you. Working example: http://sandbox.onlinephpfunctions.com/code/b20c1d17e41718661a4d0e459cdc23272a8221ed – Brian Moreno Jul 10 '17 at 18:25
  • @BrianMoreno You were correct. It was working but was outside the scope of my function. Thank you so much. – DragonKyn Jul 10 '17 at 18:37

3 Answers3

1

I think you'd need to use

echo $userrank[0]->rank

Alternatively you could return the results as an associative array using

$userrank = $result->fetchAll(PDO::FETCH_ASSOC);

and then use

echo $userrank[0]['rank']

David
  • 188
  • 1
  • 1
  • 5
0

Simply you can access your array something like this

echo $userrank[0]->rank;
Muhammad Usman
  • 1,403
  • 13
  • 24
0

Please use $userrank[0]->key ex: $userrank[0]->rank