What are the advantages and disadvantages of storing usernames and passwords in a database versus using .htaccess for security?

Storing usernames and passwords in a database allows for more flexibility and scalability in managing user accounts, as well as the ability to easily implement features like password recovery and account management. However, it also presents a higher risk of security breaches if the database is compromised. On the other hand, using .htaccess for security can provide an additional layer of protection by restricting access to certain directories or files based on user credentials, but it may be more limited in functionality compared to a database solution.

// Sample PHP code snippet to store usernames and passwords in a database

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Create table to store user credentials
$sql = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(30) NOT NULL,
    password VARCHAR(255) NOT NULL
)";

if ($conn->query($sql) === TRUE) {
    echo "Table users created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

// Insert user credentials into database
$username = "john_doe";
$password = password_hash("password123", PASSWORD_DEFAULT);

$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();