Advertisement

Google Ad Slot: content-top

MySQL Connect

~1 min read · PHP
On this page

PHP offers multiple methods to connect to a MySQL database, each with its own features and use cases. Below are the primary methods for connecting PHP to MySQL:




1. MySQLi (MySQL Improved Extension)


MySQLi is a modern, improved extension for working with MySQL databases in PHP. It supports both procedural and object-oriented approaches.

Example - Procedural Style
Example - Object-Oriented Style
connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>

Advantages of MySQLi:


  • Offers both procedural and object-oriented styles.
  • Allows multiple statements in a single query.

2. PDO (PHP Data Objects)


PDO is a database abstraction layer that supports multiple database types (not just MySQL). It's a great choice if your project might need to switch between databases in the future.



Example
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>

Advantages of PDO:


  • Supports over 12 different database systems (e.g., PostgreSQL, SQLite).
  • Allows easy error handling using exceptions.