user2957574
user2957574

Reputation: 11

Edit the contents of another page with php

So I have a simple database for logging in to my website, but i am having trouble with displaying whether or not a user has logged in.

  session_start();
  $username = $_POST['Username'];


  $salt = substr($username, 0, 2);
  $password = crypt($_POST['Password'], $salt);

  $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
  $query = $dbh->prepare("SELECT * FROM `7Ducklings` WHERE Username = ? AND Password = ?");
  $array = array($username, $password);
  $query->execute($array);
  $numrows = $query->fetchColumn();

  if($numrows == 1)
  {
    $_SESSION['Username'] = $username;
  }else{
  }
  $dbh = null;

And i want this, if the user is logged in to replace the contents of this div tag:

<div id="duckdiv">
  <form id="UserPass" method="POST" action="Check.php">
Username:<input type="text" placeholder="Username" name="Username">Password:<input type="password" placeholder="Password" name="Password">


  <a href="#"><img src="ducklogin.png"></a>
</form>
</div>

With this:

<p>"Welcome back:" $_SESSION['Username']</p>

How is this possible?

Upvotes: 0

Views: 305

Answers (1)

Igor Evstratov
Igor Evstratov

Reputation: 719

You have to start the session before using the $_SESSION superglobal array and before rendering any content.

session_start();

if($numrows == 1)
{
    $_SESSION['Username'] = $username;
}

HTML view:

<?php if (isset($_SESSION['Username'])) : ?>
    // render the welcome message
<?php else : ?>
    // render the form
<?php endif ?>

Upvotes: 1

Related Questions