How to create a database connection and how to make an ENCRYPT Password using PHP programming.

Secure PHP database connection and password encryption illustration

Creating a secure database connection and encrypting passwords are two of the most essential steps in PHP web development. Whether you are building a login system, user registration module, or any authentication-based application, understanding how to connect your PHP project to MySQL and securely hash passwords is extremely important. In this guide, you will learn how to create a database connection using both MySQLi and PDO, how to encrypt passwords using password_hash(), and how to verify them safely. This tutorial is written for beginners and intermediate developers who want to implement modern, secure practices in PHP.


Why Database Connection Matters in PHP

A database connection allows your PHP application to:

  • Store and retrieve user information
  • Validate login credentials
  • Perform CRUD operations
  • Manage roles, sessions, and authentication workflows

Without a proper connection, the application cannot communicate with MySQL, which leads to errors and security vulnerabilities. A stable and secure connection ensures smooth performance and prevents unauthorized access.


Setting Up the MySQL Database

Before writing any PHP code, you need to create a database and table.

Step 1: Create Database

  1. Open phpMyAdmin or MySQL CLI
  2. Click New
  3. Enter database name: user_system
  4. Click Create

Step 2: Create Users Table

Run the following SQL:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This structure is suitable for most authentication systems.


Creating a Database Connection Using MySQLi

MySQLi is one of the default methods used in PHP to interact with MySQL.

db_connect.php Example

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "user_system";

$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Database connected successfully!";
?>

Key Notes

  • Default local username is root
  • Production environments must use strong passwords
  • Avoid using die() in real-world sites—use error logging instead

Creating a Database Connection Using PDO (Recommended)

PDO (PHP Data Objects) is more secure and flexible.

PDO Connection Example

<?php
$host = "localhost";
$dbname = "user_system";
$user = "root";
$pass = "";

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

Why PDO Is Better

  • Supports multiple databases
  • Provides secure prepared statements
  • Better error handling through exceptions

Learn more on the official PHP documentation:
https://www.php.net/manual/en/book.pdo.php


Why You Should Never Store Plain Passwords

Storing plain passwords is one of the biggest security risks. If a database gets hacked, attackers can access every user’s login details.

Password hashing ensures:

  • Protection against data leaks
  • No readable passwords in the database
  • Industry-standard security

OWASP recommends using modern hashing algorithms like bcrypt.


Encrypting Password Using password_hash()

PHP provides an in-built, secure function:

<?php
$userPassword = "MySecret123";

$hashedPassword = password_hash($userPassword, PASSWORD_BCRYPT);

echo $hashedPassword;
?>

Features of password_hash()

  • Automatically generates a salt
  • Uses bcrypt by default
  • Cannot be reversed (one-way hashing)

Saving Encrypted Password to Database

<?php
include 'db_connect.php';

$username = "john";
$email = "john@example.com";
$password = "UserPass123";

$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $email, $hashedPassword);
$stmt->execute();

echo "User registered successfully!";
?>

Verifying Password During Login

<?php
$enteredPassword = "UserPass123";

if (password_verify($enteredPassword, $hashedPassword)) {
    echo "Login Successful!";
} else {
    echo "Invalid Password";
}
?>

Why password_verify() Is Important

  • Automatically compares hash
  • No manual salt checking required
  • Prevents timing attacks

Common Security Mistakes to Avoid

Avoid the following:

  • Using MD5 or SHA1
  • Storing passwords in plain text
  • Displaying database errors publicly
  • Using root credentials in live servers
  • Not using HTTPS

Best Practices:

  • Always use prepared statements
  • Enable SSL on hosting
  • Use environment variables
  • Regularly update PHP version

Internal & External Resources

Internal Links (Example)

  • How to Install WordPress on Localhost
  • PHP Form Validation Tutorial

External Trusted Links


Conclusion

Creating a secure database connection and encrypting passwords in PHP is essential for any modern web application. By using PDO or MySQLi, applying password hashing with password_hash() and verifying through password_verify(), you can build a safe and professional authentication system. Always follow security best practices, avoid outdated encryption methods, and protect user data with modern standards. With the right implementation, your PHP application will be secure, scalable, and ready for real-world usage.

Leave a Comment

Your email address will not be published. Required fields are marked *