In PHP, what are some common methods for allowing users to save and retrieve their data for future reference?

One common method for allowing users to save and retrieve their data for future reference in PHP is by using sessions. Sessions allow you to store user-specific data across multiple pages until the session is destroyed. Another method is using cookies, which are small pieces of data stored on the user's computer. Additionally, you can save user data in a database and retrieve it when needed.

// Start a session
session_start();

// Save user data to session
$_SESSION['user_data'] = 'Some data to save';

// Retrieve user data from session
$user_data = $_SESSION['user_data'];

// Save user data to a cookie
setcookie('user_data', 'Some data to save', time() + 3600, '/');

// Retrieve user data from a cookie
$user_data = $_COOKIE['user_data'];

// Save user data to a database
// Connect to database
$connection = mysqli_connect('localhost', 'username', 'password', 'database');

// Save user data
$user_id = 1;
$data = 'Some data to save';
mysqli_query($connection, "INSERT INTO user_data (user_id, data) VALUES ($user_id, '$data')");

// Retrieve user data
$result = mysqli_query($connection, "SELECT data FROM user_data WHERE user_id = $user_id");
$row = mysqli_fetch_assoc($result);
$user_data = $row['data'];

// Close database connection
mysqli_close($connection);