I want to display the username of the user who logs in while redirecting to the index.php However, when I run the index(Homepage) without logging in. I don't want it to display an error Notice: Undefined index: username.
index.php code:
session_start();
<?= $_SESSION['username'] ?>
login.php code:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "articleZone");
$message = "";
if (!empty($_POST["login"])) {
$result = mysqli_query($conn, "SELECT * FROM users WHERE username='" . $_POST["user_name"] . "' and password = '" . $_POST["password"] . "'");
$row = mysqli_fetch_array($result);
if (is_array($row)) {
$_SESSION["user_id"] = $row['userId'];
$_SESSION["username"] = $row['username'];
header("location: index.php");
} else {
$message = "Invalid Username or Password!";
}
}
if (!empty($_POST["logout"])) {
$_SESSION["user_id"] = "";
session_destroy();
}
?>
<?php if (empty($_SESSION["user_id"])) { ?>
form code..
<?php
} else {
$result = mysqlI_query($conn, "SELECT * FROM users WHERE userId='" . $_SESSION["user_id"] . "'");
$row = mysqli_fetch_array($result);
?>
<form action="" method="post" id="frmLogout">
<div>Welcome <?php echo ucwords($row['username']); ?>, You are now logged in.<br>