How can you retrieve the username from a MySQL database using PHP?
To retrieve the username from a MySQL database using PHP, you can establish a connection to the database, execute a SELECT query to fetch the username based on a specific condition (such as user ID), and then fetch the result from the query.
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database_name");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a SELECT query to retrieve the username based on user ID
$userID = 1; // Example user ID
$query = "SELECT username FROM users WHERE id = $userID";
$result = mysqli_query($connection, $query);
// Fetch the result and store the username in a variable
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
echo "Username: " . $username;
} else {
echo "Username not found";
}
// Close the connection
mysqli_close($connection);