PHP Connect to MySQL
🔗 PHP Connect to MySQL Tutorial
Connecting PHP to a MySQL database is the first step for any dynamic web application. You can use mysqli (procedural or object-oriented) or PDO.
1️⃣ Using mysqli (Procedural)
-
$servername→ Database host (usuallylocalhost) -
$username→ MySQL username (default:root) -
$password→ MySQL password -
$dbname→ Name of your database
✅ mysqli_connect_error() returns the error message if connection fails.
2️⃣ Using mysqli (Object-Oriented)
-
$conn->connect_errorreturns the connection error. -
$connobject is used to execute queries later.
3️⃣ Using PDO (PHP Data Objects)
PDO provides flexible and secure database access and supports multiple databases.
✅ PDO is preferred for prepared statements and database flexibility.
4️⃣ Closing the Connection
-
mysqliprocedural:
-
mysqliobject-oriented:
-
PDO: Automatically closed when
$connvariable goes out of scope.
5️⃣ Key Points
-
Check connection errors using
mysqli_connect_error()orPDOException. -
Use
mysqlifor MySQL-specific applications. -
Use PDO for secure, flexible, and multi-database applications.
-
Always close the connection after finishing database operations.
