PHP allows seamless interaction with MySQL databases for data storage, retrieval, and manipulation. There are two primary ways to connect to MySQL in PHP:
MySQLi (MySQL Improved Extension) PDO (PHP Data Objects)
Prerequisites
PHP installed on your local server (e.g., XAMPP or WAMP)
MySQL Database set up
Basic understanding of PHP and SQL
MySQL Database Configuration
Create a Sample Database and Table
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Use PDO for secure and flexible database interaction Implement prepared statements to prevent SQL Injection Use try-catch blocks for error handling Avoid hardcoding passwords in production (use environment variables)
Closing the Database Connection
MySQLi
$conn->close(); // For Object-Oriented
mysqli_close($conn); // For Procedural