To connect PHP with MySQL, you can use the mysqli
or PDO
extension. This connection allows PHP scripts to interact with the MySQL database to store, retrieve, update, or delete data. You need to specify the database host, username, password, and database name in your PHP code. The mysqli_connect()
function or new mysqli()
object is commonly used for this purpose. Always check the connection status and handle errors properly to ensure secure and stable interactions.
Step-by-Step: Connect PHP and MySQL using MySQLi
1. Create Database (example: test_db
)
You can use phpMyAdmin or run this SQL:
CREATE DATABASE test_db;
2. Create a Table
Inside test_db
, run:
sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
3. PHP File to Connect (db_connect.php
)
<?php
$servername = "localhost"; // or 127.0.0.1
$username = "root"; // default in XAMPP/WAMP
$password = ""; // default is empty
$database = "test_db"; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("❌ Connection failed: " . $conn->connect_error);
}
echo "✅ Connected successfully";
?>
To Use This Connection in Other Files
You can include it like this in other PHP files (index.php):
<?php include 'db_connect.php'; ?>