CRUD-PHPIntro

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

<?

php
// Database Connection and Login Handling

session_start();

// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpcrud";

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

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Handle login logic


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get username and password from the form
$username = $_POST['username'];
$password = $_POST['password'];

// Prepare and bind


$stmt = $conn->prepare("SELECT id, username, password FROM tblusers WHERE username = ?");
if ($stmt === false) {
die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
}

$stmt->bind_param("s", $username);

// Execute the statement


$stmt->execute();

// Bind result variables


$stmt->bind_result($id, $db_username, $db_password);

// Fetch the result


if ($stmt->fetch()) {
// Debugging: Print the hashed password from the database
// echo "Debug: Password in DB: " . $db_password . "<br>";
// echo "Debug: Entered password: " . $password . "<br>";

// Verify password
if (password_verify($password, $password)) {
// Password is correct, start a new session
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect to index.php
exit();
} else {
// Password is incorrect
echo "Invalid password.";
}
} else {
// No user found with that username
echo "No user found with that username.";
}

// Close the statement and connection


$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login.php" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>

You might also like