I can't bring up the logged-in user session in login.php to the coba.php page and there is an error "undefined array key" in coba.php. how do I make it so that in coba.php the error does not appear and can bring up the logged-in user session in the form of the username
login.php
<?php
session_start();
include "koneksi.php";
$username=$_POST['username'];
$password=$_POST['password'];
$cek_data= mysqli_query($conn,"select * from anggota where username='$username' and password='$password'");
$cek = mysqli_num_rows($cek_data);
if ($cek>0){
$data = mysqli_fetch_assoc($cek_data);
$_SESSION['username'] = $username;
echo "Berhasil Login";
}else {
echo "Gagal Login";
}
?>
coba.php
<?php
session_start();
echo $_SESSION['username'];
?>
I'm trying to get the user username into try.php without the error undefined array key "Username"
CodePudding user response:
It looks like the issue is that you are trying to access the 'username' key of the $_SESSION array in coba.php, but it is not set.
One possible solution to this problem is to check if the 'username' key is set in the $_SESSION array before trying to access it. You can do this by using the isset() function in PHP, which returns a boolean indicating whether the given variable is set and is not NULL.
Here's how you can modify the code in coba.php to check if the 'username' key is set:
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
echo "Username is not set.";
}
?>
If the 'username' key is set, this code will print the username. If it is not set, it will print a message indicating that the key is not set.
I hope this helps! Let me know if you have any other questions.
CodePudding user response:
To bring the logged-in user's session from the login.php page to the coba.php page, you need to start the session in coba.php using session_start(). This will allow you to access the session variables that were set in login.php.
To fix the "undefined array key" error, you need to make sure that the $_SESSION['username'] variable is set before trying to access it. You can do this by checking if the $_SESSION['username'] variable is set before trying to access it in coba.php
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
// display an error message or redirect to the login page
}
?>
This code will start the session, and then check if the $_SESSION['username'] variable is set. If it is set, it will print the value of the $_SESSION['username'] variable. If it is not set, it will display an error message or redirect the user back to the login page