What are the advantages of using IDs instead of usernames in MySQL queries in PHP?

Using IDs instead of usernames in MySQL queries in PHP can improve performance and security. IDs are typically indexed in the database, making lookups faster compared to querying by usernames. Additionally, using IDs can help prevent SQL injection attacks by avoiding the need to directly insert user input (such as usernames) into queries.

// Example of using IDs instead of usernames in MySQL queries in PHP

// Assuming $userId is the ID of the user you want to retrieve
$userId = 1;

// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");

// Prepare and execute the query using the user ID
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();

// Fetch the results
$result = $stmt->get_result();
$user = $result->fetch_assoc();

// Close the connection
$conn->close();

// Output the user data
echo "Username: " . $user['username'];
echo "Email: " . $user['email'];