-2

I am trying for ours to get this working and I don't understand what is wrong, I am trying to call a function from the index page that will be returning the name of a user from a table in mysql. I call a function called getusername() from index.php the function is located in func.php that is already included in the index page. When I call a different function located in the func.php is working just fine except this one.

The table in mysql is called user and has the following attributes userID,Role,Username

The function I called has the following source code

function getusername() {



    $query= mysql_query("SELECT * FROM user WHERE UserID=1");

   $id = 'UserID';
   $role = 'Role';
   $username = 'Username'; 


    $rows = mysql_fetch_assoc($query);


    echo $username;
}

No matter how many times I tried I cant echo the users name that has id=1 can please anybody help me ?

Abhishek
  • 539
  • 5
  • 25
user3397260
  • 241
  • 5
  • 17
  • 1
    FYI, [you shouldn't use `mysql_*` functions in new code](http://stackoverflow.com/questions/12859942/). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](http://php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](https://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which one is best for you. – John Conde Nov 04 '17 at 16:24

1 Answers1

1

You don't need to define single vars, everything you have in the array (in example called $row, better would be $user).

Than you are using old mysql_ extension, which is removed from current PHP versions. Use PDO or at least mysqli instead.

$query = mysql_query("SELECT * FROM user WHERE UserID = 1");
$row = mysql_fetch_assoc($query);
print_r($row); // array, username is in $row['username'];
pavel
  • 26,538
  • 10
  • 45
  • 61