How can a login system with multiple users and MySQL be implemented in PHP?
To implement a login system with multiple users and MySQL in PHP, you can create a users table in your MySQL database to store user credentials. When a user tries to log in, you can query the database to check if the provided username and password match any records in the users table. If a match is found, you can create a session for that user to keep them logged in.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Login form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
// Start session and redirect to dashboard
session_start();
$_SESSION['username'] = $username;
header("Location: dashboard.php");
} else {
echo "Invalid username or password";
}
}
$conn->close();
?>
Keywords
Related Questions
- Are there any specific PHP scripts or tools recommended for managing user accounts and domains in a free web hosting service?
- Are there potential security risks when accessing session variables on a local Apache server with PHP?
- What steps should be taken to ensure that PHP scripts, HTML, database, and data transfer between PHP and the database are all set to UTF-8 encoding?