How can two tables be linked in PHP to retrieve user-specific data for profile editing?
To link two tables in PHP to retrieve user-specific data for profile editing, you can use a JOIN query to combine the data from both tables based on a common identifier, such as user ID. This allows you to fetch the necessary information from both tables in a single query.
<?php
// Assuming you have two tables: users and profile_data
$user_id = 1; // The user ID for which you want to retrieve data
// Connect to your database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve user-specific data for profile editing
$sql = "SELECT users.*, profile_data.* FROM users
JOIN profile_data ON users.user_id = profile_data.user_id
WHERE users.user_id = $user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. "<br>";
echo "Email: " . $row["email"]. "<br>";
echo "Profile Info: " . $row["profile_info"]. "<br>";
// Add more fields as needed
}
} else {
echo "0 results";
}
$conn->close();
?>
Related questions
-
PHP JavaScript output
-
PHP database retrieval session storage
-
PHP SQL database