Trying to display user content in a profile page

When i go to my profile page is empty.

template_class.php

class Template
{	
	public $arr= array();
	public $layouts;

		public function add_content($pag,$arr)
		{
			$var=file_get_contents('template/'.$pag);
			foreach($arr as $key => $value)
			{
				$var=str_replace('{{'.$key.'}}',$value,$var);
			}
			
			$this->arr[] = $var;
		
		}

		public function set_layout($lay)
		{
			$this->layouts=$lay;
		}

		public function show()
		{	
			
			if(!file_exists('template/'.$this->layouts))
			{
				$layout=file_get_contents('template/homepage.tpl');
			}
			else
			{
				$layout=file_get_contents('template/'.$this->layouts);
			}

			$content='';
			
			foreach($this->arr as $key=>$value)
			{
				$content .= $value;
	
			}
			$layout=str_replace('{{CONTENT}}',$content,$layout);

			
			echo $layout;
		}
}

home.php

require './template_class.php';


$template= new Template();

$template->set_layout('homepage.tpl');

$visib='';
$disp='';

if(isset($_COOKIE['Login']) & isset($visib) & isset($disp))
{
	$visib='visible';
	$disp='invisible';
}
else
{
	$visib='invisible';
	$disp='visible';
}

$template->add_content('home.tpl',array(
										'visibility' => $visib,
										'display' => $disp,
										));


$template->show();

homepage.tpl

<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
  <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="home.php">Home</a>
    </li>
	<li class="nav-item">
      <a class="nav-link" href="profile.php">Profile</a>
    </li>
  </ul>
	{{CONTENT}}
</nav>

home.tpl

   <ul class="nav navbar-nav ml-auto">
      <li class="nav-item">
        <a class="nav-link {{display}}" href="user/form_login.php"><span class="fas fa-sign-in-alt"></span> Login</a>
      </li>
	  <li class="nav-item">
        <a class="nav-link {{display}}" href="user/form_register.php"><span class="fas fa-user"></span> Sign Up</a>
      </li>
	   <li class="nav-item">
	   <a class="nav-link  {{visibility}}" href="user/logout.php" ><span class="fas fa-user"></span> Logout</a>
	   </li>
    </ul>

form_login.php

  <form action="login.php">
     <div class="form-group">
      <label for="user name">Username:</label>
      <input type="text" class="form-control" id="user" placeholder="Enter user" name="user">
    </div>
    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
    </div>
    <div class="form-group form-check">
      <label class="form-check-label">
        <input class="form-check-input" type="checkbox" name="remember"> Remember me
      </label>
    </div>
    <button type="submit" class="btn btn-primary" name="login_user">Log in</button>
  </form>

login.php

<?php

setcookie("Login","You are loged in.", time()+ 99999999, "/");

require 'user_con.php';

$username=$_POST['username'];
$password=$_POST['password'];
$errors = array();

  if (empty($username)) {
  	array_push($errors, "Username is required");
  }
  if (empty($password)) {
  	array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {

$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password' LIMIT 1";
$result = mysqli_query($link,$sql);

 }
 else 
 {
  	array_push($errors, "Wrong username/password combination");
 }
 
header('Location:../home.php');

profile.php

<?php

require './template_class.php';
require './user/user_con.php';

$template= new Template();

$template->set_layout('view_profile.tpl');

$userid=$_POST['userid'];

$sql = "SELECT username, fname, lname, email, number FROM $tbl_name WHERE userid='$userid' LIMIT 1";
$result = mysqli_query($link,$sql);
$rows = mysqli_num_rows($result);


while($rows)
{

$template->add_content('profile.tpl',array(
										'First name' => $rows['fname'],
										'Last name' => $rows['lname'],
										'Email' => $rows['email'],
										'Phone Number' => $rows['number'],
										));

}

$template->show();

mysqli_close($link);

view_profile.tpl

  <table class="table table-dark">
    <thead>
	<tr>
	<th>First name</th>
	<th>Last name</th>
	<th>Email</th>
	<th>Phone Number</th>
	</tr>
    </thead>
    <tbody>
	{{CONTENT}}
	</tbody>
  </table>

profile.tpl

	<tr>
	<td>{{First name}}</td>
	<td>{{Last name}}</td>
	<td>{{Email}}</td>
	<td>{{Phone Number}}</td>
	</tr>	

I don’t know what platform you’re using on top of PHP, but this bit doesn’t look correct to me:

$rows = mysqli_num_rows($result);


while($rows)
{

$template->add_content('profile.tpl',array(
  'First name' => $rows['fname'],
  'Last name' => $rows['lname'],
  'Email' => $rows['email'],
  'Phone Number' => $rows['number'],
));

}

I’m surprised that doesn’t result in an infinite loop, and some error messages. The infinite loop because $rows is not altered during the loop, so if the loop ever runs, it will run for ever. The error messages because $rows is a number before the loop (the number of rows returned from your query) but you are treating it as an array inside the loop.

You’ve executed the query and got a pointer to the results in $result, but you need to use one of the fetch functions to retrieve the data. The while() loop is superfluous because the query will only return one row. You should just check that the query ran, check it returned a single row, then fetch the details and use them.

I change it to:

while($rows=mysqli_fetch_array($result))
{

$template->add_content('profile.tpl',array(
										'First name' => $rows['fname'],
										'Last name' => $rows['lname'],
										'Email' => $rows['email'],
										'Phone Number' => $rows['number'],
										));
}

To be clear, did this resolve the problem?

No it is still empty.

I suspect droop’s hit it on the head, without actually naming the problem.

The fact that the loop WASNT running forever seems to indicate to me that $rows is one of two things:

  1. 0, which is falsey, and so yes, you had 0 rows returned, so you get a blank template when it runs across 0 records.
  2. undefined, which means your query borked.

Change:

$sql = "SELECT username, fname, lname, email, number FROM $tbl_name WHERE userid='$userid' LIMIT 1";
$result = mysqli_query($link,$sql);
$rows = mysqli_num_rows($result);

into

$sql = "SELECT username, fname, lname, email, number FROM $tbl_name WHERE userid='$userid' LIMIT 1";
$result = mysqli_query($link,$sql);
if(!$result) { echo mysqli_error($link); die(); } 
$rows = mysqli_num_rows($result);
//Temporary, remove after verifying.
echo $rows

and see what you get.

Also note that your code is now overwriting the value of $rows while it does its loop.

Additional: Strongly suggest you investigate using prepared statements, as your code is extremely vulnerable to SQL injection attacks.

The result is 0.
Maybe my login page is at fault.

echo $sql out and verify it looks correct. It’ll at least narrow down where your problem is.

The echo for $sql SELECT username, fname, lname, email, number FROM users WHERE userid=‘’ LIMIT 1

looks to me like your variable was empty, so it returned no records, because userid is never empty.

What field in your form is filling this out?

There seems to be a few anomalies in there. For example the login form says

<input type="text" class="form-control" id="user" 
    placeholder="Enter user" name="user">

but login.php says

$username=$_POST['username'];

That file checks for the form variables being empty, though, so you’d imagine it would fall over earlier.

This is another strange thing -

<form action="login.php">

Because there is no “method” specified, it will default to submitting using the “GET” method. So the login.php should fail, because none of the $_POST variables used will be set. Unless the platform the OP is using has some JavaScript code to do the submitting, in which case both of the above issues might not be issues. If you have JS code that changes input variable names, though, I’d suggest that is confusing and not good practice.

This is a bit concerning too, though -

$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password' LIMIT 1";

Never, ever, ever store plain-text passwords in your database. Read up on password_hash() and password_verify()` instead.

Your link to the profile page seems to be:

<a class="nav-link" href="profile.php">Profile</a>

so there’s never going to be a $_POST array to be getting your user id from.

I change the next files like this:

login.php

<?php

if(isset($_POST['login_user']))
{
	require 'user_con.php';
	
	$username = $_POST['nameuser'];
	$password = $_POST['pwd'];
	
	if(empty($username) || empty($password))
	{
		header('Location:../home.php?error=emptyfields');
		exit();
	}
	else
	{
		$sql="SELECT * FROM $tbl_name WHERE username=?";
		$stmt = mysqli_stmt_init($link);
		if(!mysqli_stmt_prepare($stmt,$sql))
		{
			header('Location:../home.php?error=sqlerror');
			exit();
		}
		else
		{
			mysqli_stmt_bind_param($stmt,'s',$username);
			mysqli_stmt_execute($stmt);
			$result = mysqli_stmt_get_result($stmt);
			if($row = mysqli_fetch_assoc($result))
			{
				$passwordcheck = password_verify($password,$row['password']);
				if($passwordcheck == false)
				{
					header('Location:../home.php?error=wrongpassword');
					exit();	
				}
				elseif($passwordcheck == true)
				{
					session_start();
					$_SESSION['useri']= $row['userid'];
					$_SESSION['usern']= $row['username'];
					
				header('Location:../home.php?login=success');
				exit();
				}
			}
			else
			{
				header('Location:../home.php?error=nouser');
				exit();
			}
		}
	}
	mysqli_stmt_close($stmt);
	mysqli_close($link);
}
else
{
	header('Location:../home.php?error');
	exit();
}

form_login.php


<form method="post" action="login.php">
     <div class="form-group">
      <label for="username">Username:</label>
      <input type="text" class="form-control" id="nameuser" placeholder="Enter user" name="nameuser">
    </div>
    <div class="form-group">
      <label for="password">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
    </div>
    <button type="submit" class="btn btn-primary" name="login_user">Log in</button>
  </form>

template_class.php i added this:

	public $arr2= array();
	public function add_content2($pag,$arr)
	{
	        $var=file_get_contents('template/'.$pag);
		foreach($arr as $key => $value)
		{
			$var=str_replace('{{'.$key.'}}',$value,$var);
		}
			
		$this->arr2[] = $var;
		
		}
		$content2='';
			
		foreach($this->arr2 as $key=>$value)
		{
			$content2 .= $value;
	
		}
		$layout=str_replace('{{CONTENT2}}',$content2,$layout);

home.php :

session_start();

require './template_class.php';

$template= new Template();

$template->set_layout('homepage.tpl');

$template->set_title('Home');

$template->set_header('header.tpl');

$template->set_subtitle('Welcome to our site');


$visib='';
$disp='';
$userid = isset($_SESSION['useri']);

if($userid && isset($visib) && isset($disp))
{
	$visib='visible';
	$disp='invisible';
}
else
{
	$visib='invisible';
	$disp='visible';
}

$template->add_content('home.tpl',array(
										'visibility' => $visib,
										'display' => $disp,
										));

$template->add_content2('home2.tpl',array(
										'id' => $userid,
										));


$template->show();

homepage.tpl

<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
   <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="home.php">Home</a>
    </li>
	<li class="nav-item">
      {{CONTENT2}}
    </li>
  </ul>
	{{CONTENT}}
</nav>

added a new file home2.tpl

<a class="nav-link" href="profile.php?{{id}}">Profile</a>

and profile.php

session_start();
require './template_class.php';
require './user/user_con.php';

$template= new Template();

$template->set_layout('view_profile.tpl');

$template->set_title('Profile');

$template->set_header('header.tpl');

$template->set_subtitle('Your Profile');

$userid=isset($_SESSION['useri']);

$sql = "SELECT username, fname, lname, email, number FROM $tbl_name WHERE userid='$userid' LIMIT 1";

$result = mysqli_query($link,$sql);

while($rows=mysqli_fetch_assoc($result))
{

$template->add_content('profile.tpl',array(
										'First name' => $rows['fname'],
										'Last name' => $rows['lname'],
										'Email' => $rows['email'],
										'Phone Number' => $rows['number'],
										));

}

$template->show();

mysqli_close($link);

The problem is that the profile is still not working.

And what was the result?

This is a problem, in profile.php:

$userid=isset($_SESSION['useri']);

$sql = "SELECT username, fname, lname, email, number 
   FROM $tbl_name WHERE userid='$userid' LIMIT 1";

If you look at the doc for isset(), it returns either true or false. So you’re checking to see whether that session variable exists, and assigning that to $userid. You’re not getting the value of the userid, just a Boolean to say if it exists. So you can’t use that Boolean as the userid. Once you know it exists, then you can recover its value from the session variable and use it. There’s a similar problem in home.php.

And how to i recover the value from the session varibale

Never mind i did it thank you for the help.

I have a little problem if no user is login i get this error:

( ! ) Notice: Undefined index: useri in C:\net\www\users\home.php on line *23*
Call Stack
# Time Memory Function Location
1 0.0001 401872 {main}( ) ...\home.php **:** 0

Show us the code that produces that error message.

I suspect that you’ve removed your isset() check, and now just try to retrieve the value of the session variable. You can’t do that - before you try to use the session variable, you must check that it exists.

I did it like this:

if(isset($_SESSION['useri']))
{
	$userid = $_SESSION['useri'];
}

Look very closely at what’s wrong with the first line of that code.