How can I troubleshoot issues with a self-written login system in PHP?

Issue: If you are experiencing issues with your self-written login system in PHP, it could be due to incorrect validation of user credentials or database connection problems. To troubleshoot, double-check your SQL queries, ensure the database connection is established correctly, and verify that user input is sanitized and validated.

// Example code snippet to troubleshoot login issues in PHP

// Check database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Validate user credentials
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // Login successful
    session_start();
    $_SESSION['username'] = $username;
    header("Location: dashboard.php");
} else {
    // Login failed
    echo "Invalid username or password";
}

$stmt->close();
$conn->close();