How to display updated data in php session

I created a projects that uses session but whenever i user tries to update my name in settings, i need to logout and login before the updated data reflects dashboard.
How do I make it reflects without the logout and login process?

Example of my setting source code is:

<?php

// php code to Update data from mysql database Table

if(isset($_POST['update']))
{
    
    $hostname = "localhost";
    $username = "";
    $password = "";
    $databaseName = "mdb";
   
    $connect = mysqli_connect($hostname, $username, $password, $databaseName);
   
    // get values form input text and number
    $name = $_POST['name']; 
    $amount = $_POST['amount'];
    $email_id = $_POST['email_id'];

    // mysql query to Update data
    $query = "UPDATE `users` 
                SET `name`='".$name."',
                `amount`= $amount 
               WHERE `email_id` = $email_id";
   
    $result = mysqli_query($connect, $query);
   
    if($result){
       echo '<div class="alert alert-success" role="alert">
 Updated successfully!
</div>';
    }else{
       echo 'Data Not Updated';
    }
    mysqli_close($connect);
}
?>
 <!-- * And this is the HTML -->
<form id="my-form" action="" method="post">
    <input type="number" name="email_id" >
    <input type="text" name="name">
    <input  type="text" name="amount">
    <button type="submit" name="update">Update</button>
</form>

<!-- * session data display -->

<?php
session_start();

if(isset($_SESSION['userdata'])){
$user = $_SESSION['userdata'][0];    
}
?>

<h2><?=$user['name']?></h2>

Can any one help?

Insert mysql credentials from cpanel

Instead of using sessions, just load the information directly from the database. You have connection already open anyways.

Additionally, you are vulnerable to SQL injection, which could lead to a data breach, deletion, etc.

4 Likes

As generally good practice, I would recommend to always put the session_start() line a the very top of the file.

I think it’s also the reason your code may not work: you run an echo statement before doing session_start(). Running echo means the request header is closed and the server starts sending the response content. But to start a session, PHP needs to add some additional information to be header, which it can’t do if the server is already sending the body.

5 Likes

It’s just a test project, i’m new into php web development

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.