0

I am trying to make the following code to be a php variable. The idea is so I can get all the user data I need by giving the variable the id of the user.

$sql = "SELECT * FROM `users` WHERE user_id='$user_id'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while ($row = $result->fetch_assoc()) {
    $displayname = $row['user_displayname'];
  }
}

"display name" here is what I want to get.

It works when not in a function but it does not work in the function. Perhaps I am doing something wrong, here. is how I am doing it.

function get_userdetails($user_id) {

// Figure out displayname of rulechanger
$sql = "SELECT * FROM `users` WHERE user_id='$user_id'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while ($row = $result->fetch_assoc()) {
    $displayname = $row['user_displayname'];
  }
 }
}

Thanks in advance!

1 Answers1

0

Presumably $conn is a global variable (object) representing your database connection. In order to access it inside a function you need to use the global keyword - in this case global $conn;

You will need to do the same with $displayname if you intend to refer to it outside of the function (after the function has set its value). Probably best here will be to simply return $displayname from your function.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34