Skip to main content

Contact Management Using Php

· 6 min read
Sivabharathy

In this article, we will create a simple user registration, login, and contact management system using PHP and MySQL, styled with Tailwind CSS. We will cover the entire process, from database setup to user interface design.

Prerequisites

  • Basic knowledge of PHP and SQL.
  • A web server with PHP and MySQL (e.g., XAMPP, MAMP).
  • Tailwind CSS for styling.

Step 1: Set Up the Database

Create a Database and Tables

  1. Create a Database: Use phpMyAdmin or a MySQL client to create a database named contact_management.

  2. Create the Tables:

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);

CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(100) NOT NULL,
email VARCHAR(100),
phone VARCHAR(15),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

Step 2: Project Structure

Create the following directory structure:

/contact_management
/css
- tailwind.css
/includes
- db.php
- functions.php
- register.php
- login.php
- contacts.php
- logout.php

Step 3: Database Connection (includes/db.php)

Create a database connection file:

<?php
$host = 'localhost';
$db = 'contact_management';
$user = 'root'; // Update as needed
$pass = ''; // Update as needed

try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Step 4: User Registration (register.php)

Create a registration page:

<?php
session_start();
include 'includes/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
if ($stmt->execute([$username, $password])) {
header("Location: login.php");
} else {
echo "<p class='text-red-500 text-center'>Registration failed!</p>";
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<title>Register</title>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded shadow-md w-96">
<h2 class="text-2xl font-bold mb-6 text-center">Register</h2>
<form method="POST">
<input type="text" name="username" class="border border-gray-300 p-2 mb-4 w-full rounded" placeholder="Username" required>
<input type="password" name="password" class="border border-gray-300 p-2 mb-4 w-full rounded" placeholder="Password" required>
<button type="submit" class="bg-blue-500 text-white p-2 rounded w-full hover:bg-blue-600">Register</button>
</form>
<p class="mt-4 text-center">Already have an account? <a href="login.php" class="text-blue-500 hover:underline">Login here</a>.</p>
</div>
</body>
</html>

Step 5: User Login (login.php)

Create a login page:

<?php
session_start();
include 'includes/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
header("Location: contacts.php");
} else {
echo "<p class='text-red-500 text-center'>Invalid credentials!</p>";
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<title>Login</title>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded shadow-md w-96">
<h2 class="text-2xl font-bold mb-6 text-center">Login</h2>
<form method="POST">
<input type="text" name="username" class="border border-gray-300 p-2 mb-4 w-full rounded" placeholder="Username" required>
<input type="password" name="password" class="border border-gray-300 p-2 mb-4 w-full rounded" placeholder="Password" required>
<button type="submit" class="bg-blue-500 text-white p-2 rounded w-full hover:bg-blue-600">Login</button>
</form>
<p class="mt-4 text-center">Don't have an account? <a href="register.php" class="text-blue-500 hover:underline">Register here</a>.</p>
</div>
</body>
</html>

Step 6: Contact Management (contacts.php)

Create a contact management page with add, edit, and delete functionalities:

<?php
session_start();
include 'includes/db.php';

if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}

// Add new contact
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_contact'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$user_id = $_SESSION['user_id'];

$stmt = $pdo->prepare("INSERT INTO contacts (user_id, name, email, phone) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_id, $name, $email, $phone]);
}

// Edit contact
if (isset($_GET['edit'])) {
$contact_id = $_GET['edit'];
$stmt = $pdo->prepare("SELECT * FROM contacts WHERE id = ? AND user_id = ?");
$stmt->execute([$contact_id, $_SESSION['user_id']]);
$contact = $stmt->fetch();
}

// Update contact
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_contact'])) {
$contact_id = $_POST['contact_id'];
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];

$stmt = $pdo->prepare("UPDATE contacts SET name = ?, email = ?, phone = ? WHERE id = ? AND user_id = ?");
$stmt->execute([$name, $email, $phone, $contact_id, $_SESSION['user_id']]);
header("Location: contacts.php");
}

// Delete contact
if (isset($_GET['delete'])) {
$contact_id = $_GET['delete'];
$stmt = $pdo->prepare("DELETE FROM contacts WHERE id = ? AND user_id = ?");
$stmt->execute([$contact_id, $_SESSION['user_id']]);
header("Location: contacts.php");
}

// Fetch contacts
$stmt = $pdo->prepare("SELECT * FROM contacts WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$contacts = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<title>Contacts</title>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
<header class="bg-blue-600 text-white p-4">
<h1 class="text-2xl">Contact Management</h1>
<a href="logout.php" class="text-white hover:underline">Logout</a>
</header>
<main class="flex-grow container mx-auto p-4">
<div class="bg-white p-6 rounded shadow-md">
<h2 class="text-xl font-bold mb-4">Add/Edit Contact</h2>

<form method="POST" class="mb-4">
<input type="hidden" name="contact_id" value="<?php echo isset($contact) ? $contact['id'] : ''; ?>">
<input type="text" name="name" class="border border-gray-300 p-2 mb-2 w-full rounded" placeholder

="Name" required value="<?php echo isset($contact) ? htmlspecialchars($contact['name']) : ''; ?>">
<input type="email" name="email" class="border border-gray-300 p-2 mb-2 w-full rounded" placeholder="Email" value="<?php echo isset($contact) ? htmlspecialchars($contact['email']) : ''; ?>">
<input type="text" name="phone" class="border border-gray-300 p-2 mb-4 w-full rounded" placeholder="Phone" value="<?php echo isset($contact) ? htmlspecialchars($contact['phone']) : ''; ?>">
<button type="submit" name="<?php echo isset($contact) ? 'update_contact' : 'add_contact'; ?>" class="bg-blue-500 text-white p-2 rounded w-full hover:bg-blue-600">
<?php echo isset($contact) ? 'Update Contact' : 'Add Contact'; ?>
</button>
</form>

<h2 class="text-xl font-bold mb-4">Your Contacts</h2>
<ul class="space-y-2">
<?php foreach ($contacts as $contact): ?>
<li class="border-b py-2 flex justify-between items-center">
<span class="font-semibold"><?php echo htmlspecialchars($contact['name']); ?></span>
<div>
<a href="?edit=<?php echo $contact['id']; ?>" class="text-blue-500 hover:underline">Edit</a>
<a href="?delete=<?php echo $contact['id']; ?>" class="text-red-500 hover:underline ml-4">Delete</a>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
</main>
</body>
</html>

Step 7: Logout Functionality (logout.php)

Create a logout script:

<?php
session_start();
session_destroy();
header("Location: login.php");
exit();
?>

Step 8: Styling with Tailwind CSS

Make sure you include the Tailwind CSS CDN link in the <head> section of each HTML file as shown above. You can customize the styles based on your design preferences.

Conclusion

You now have a complete user registration and contact management system. Users can register, log in, and manage their contacts by adding, editing, and deleting them.

Security Considerations

  • Ensure that you validate and sanitize user inputs to prevent SQL injection and XSS attacks.
  • Implement password policies and session management best practices to secure user data.

Next Steps

You can extend this application by adding features such as:

  • User roles and permissions.
  • Additional fields for contacts (e.g., address, notes).
  • Search functionality for contacts.
  • Frontend frameworks like Vue.js or React for a more dynamic user interface.