PHP Connect to MySQL

PHP Connect to MySQL Tutorial
PHP Connect to MySQL database is the first step for any dynamic web application. You can use mysqli (procedural or object-oriented) or PDO.
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.
Using mysqli (Object-Oriented)
$conn->connect_errorreturns the connection error.$connobject is used to execute queries later.
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.
Closing the Connection
mysqliprocedural:
mysqliobject-oriented:
PDO: Automatically closed when
$connvariable goes out of scope.
MySQLi vs PDO Comparison
- MySQLi is simple and MySQL-only
- PDO supports multiple databases
- PDO supports named parameters
- Both support prepared statements
For beginners, MySQLi is easier. For advanced projects, PDO is recommended.
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.
