PHP Sessions and Cookies

PHP MySQL Connection – Connect to Database Easily 🛢️

Want to store user data, login details, or even cat memes? 🐱 PHP and MySQL make it possible! To interact with MySQL databases, PHP provides two popular methods:

  • MySQLi (Improved MySQL extension)
  • PDO (PHP Data Objects – supports multiple databases)

🔹 Method 1: Connecting with MySQLi (Procedural)

The simplest way to connect PHP with MySQL is using mysqli_connect().

📝 Example: MySQLi Connection (Procedural)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>

Try It Now


🔹 Method 2: Connecting with MySQLi (Object-Oriented)

Another approach using MySQLi but in an object-oriented style:

📝 Example: MySQLi Connection (OOP)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>

Try It Now


🔹 Method 3: Connecting with PDO

PDO is a secure and flexible way to connect PHP with MySQL and other databases.

📝 Example: PDO Connection

<?php
$dsn = "mysql:host=localhost;dbname=my_database";
$username = "root";
$password = "";

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Try It Now


🎯 Key Takeaways

  • MySQLi Procedural: Simple and easy.
  • MySQLi OOP: More structured.
  • PDO: Supports multiple databases and provides better security.

📝 Practice Time!

Try modifying the database credentials and see what happens! Can you handle connection errors better? 🤔