Advertisement

Google Ad Slot: content-top

MySQL Connect


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
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($conn);
?>

Example - Object-Oriented Style
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypassword";
$dbname = "mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->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
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypassword";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set error mode to exception
$conn->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.