How do I connect to MySQL database in PHP (PDO vs MySQLi)?

Connecting to a MySQL database in PHP can be done using either the PDO (PHP Data Objects) or MySQLi (MySQL Improved) extension. Both extensions provide a way to interact with your database, but they have different features and advantages.

Using PDO to Connect to MySQL

PDO offers a data-access abstraction layer, which means you can use the same functions to interact with different types of databases. Here’s how you can connect to a MySQL database using PDO:

<?php // Database configurations $host = 'localhost'; $db = 'your_database'; $user = 'your_username'; $pass = 'your_password'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); echo "Connected to the database successfully!"; } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); } ?>

Using MySQLi to Connect to MySQL

MySQLi is specific to MySQL and offers both procedural and object-oriented approaches. Here’s how to connect to a MySQL database using MySQLi:

<?php // Database configurations $host = 'localhost'; $user = 'your_username'; $pass = 'your_password'; $db = 'your_database'; // Create connection $mysqli = new mysqli($host, $user, $pass, $db); // Check connection if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } echo "Connected to the database successfully!"; ?>

PDO MySQLi PHP MySQL connection database access PHP Data Objects MySQL Improved