How can PHP developers ensure that only authenticated users are able to access and view their own data in a database query?
To ensure that only authenticated users can access and view their own data in a database query, PHP developers can implement user authentication and authorization mechanisms. This can be achieved by requiring users to log in with their credentials and then checking their access rights before executing any database queries.
// Check if user is authenticated
session_start();
if(!isset($_SESSION['user_id'])) {
// Redirect to login page or display an error message
header("Location: login.php");
exit();
}
// Get user ID from session
$user_id = $_SESSION['user_id'];
// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare and execute query to fetch user's data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
// Fetch and display user's data
$user_data = $stmt->fetch();
echo "Welcome, " . $user_data['username'] . "! Your email is: " . $user_data['email'];