PHP Connect to MySQL

PHP Tutorial

 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 (usually localhost)

  • $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_error returns the connection error.

  • $conn object 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

  • mysqli procedural:


 

  • mysqli object-oriented:


 

  • PDO: Automatically closed when $conn variable 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

  1. Check connection errors using mysqli_connect_error() or PDOException.

  2. Use mysqli for MySQL-specific applications.

  3. Use PDO for secure, flexible, and multi-database applications.

  4. Always close the connection after finishing database operations.

You may also like...