Reputation: 1353
I have looked at other Stack Overflow questions and none of them fixed the issue. The following class defines the variable and then calls the variable in the HTML code.
I've used this same method for another PHP page and it works perfectly. For some reason it does not work on this page. I've done it like this numerous times without any issues. PhpStorm says the variable $user "might not have been defined", but I know it is. How can I fix this?
I have tried setting the variable global at the top of the page without luck. I have tried setting the variable global after if(isset()) and still doesn't work. Here's my PHP code:
<?php
session_start();
require_once 'includes/class.user.php';
$user_edit = new USER();
if(!$user_edit->is_logged_in())
{
$user_edit->redirect('index.php');
}
if(isset($_GET['user_id'])) {
$tid = $_GET['user_id'];
$stmt = $user_edit->runQuery("SELECT * FROM users WHERE user_id = :id");
$stmt->execute(array(':id' => $tid));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<?php include('header.php'); ?>
<div class="container side-collapse-container">
<p><?php if (!empty($user['username'])) {
echo $user['username'];
} ?></p>
</div>
<?php include('footer.php'); ?>
This is what is shown in the browser after running it with XAMPP
Notice: Undefined variable: user in C:\Users\USER\PhpstormProjects\site1\view_user.php on line 22
Upvotes: 2
Views: 2866
Reputation: 106
PhpStorm is saying the $user variable might not be defined because it is currently set in a 'if' block. If you want the PhpStorm msg to go away, define $user above the 'if' as an array.
$user = [];
if (isset($_GET['user_id'])) {
$tid = $_GET['user_id'];
$stmt = $user_edit->runQuery("SELECT * FROM users WHERE user_id = :id");
$stmt->execute(array(':id' => $tid));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
If the user name is not showing on the page, then the query is either returning as empty (false) or the index 'username' is incorrect.
Of course, for $user to be populated, user_id needs to be in the query string.
Upvotes: 5
Reputation: 468
Define $user
at first
$user = array();
// your codes
Check $user
before calling
if (isset($user['username']) && !empty($user['username'])) {
// your codes
Upvotes: 2