Certainly! If you want to implement a login and register system using PHP with PDO (PHP Data Objects) and Object-Oriented Programming (OOP) principles, you can follow the steps below. I’ll provide a simple example to get you started.
Let’s create a basic class for database connection (DbConnection
), a class for user operations (User
), and a simple login/register script.
- DbConnection.php:
<?php
class DbConnection
{
private $host = 'your_host';
private $db_name = 'your_database';
private $username = 'your_username';
private $password = 'your_password';
private $conn;
public function connect()
{
$this->conn = null;
try {
$this->conn = new PDO(
'mysql:host=' . $this->host . ';dbname=' . $this->db_name,
$this->username,
$this->password
);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
return $this->conn;
}
}
?>
- User.php:
<?php
class User
{
private $conn;
public function __construct($db)
{
$this->conn = $db;
}
public function register($username, $password)
{
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = 'INSERT INTO users (username, password) VALUES (:username, :password)';
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $hashed_password);
if ($stmt->execute()) {
return true;
} else {
return false;
}
}
public function login($username, $password)
{
$query = 'SELECT id, username, password FROM users WHERE username = :username';
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
$hashed_password = $row['password'];
if (password_verify($password, $hashed_password)) {
return $row;
} else {
return false;
}
} else {
return false;
}
}
}
?>
- index.php:
<?php
require_once 'DbConnection.php';
require_once 'User.php';
// Database connection
$database = new DbConnection();
$db = $database->connect();
// User object
$user = new User($db);
// Example usage for registration
$username = 'example_user';
$password = 'example_password';
if ($user->register($username, $password)) {
echo 'Registration successful!';
} else {
echo 'Registration failed!';
}
// Example usage for login
$login_username = 'example_user';
$login_password = 'example_password';
$logged_in_user = $user->login($login_username, $login_password);
if ($logged_in_user) {
echo 'Login successful! Welcome, ' . $logged_in_user['username'] . '!';
} else {
echo 'Login failed!';
}
?>
Remember to replace the placeholders (your_host
, your_database
, your_username
, your_password
) with your actual database connection details.
This is a basic example, and you might want to enhance it by adding features such as session management, error handling, input validation, etc., based on your specific requirements.