Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

2. PHP Database APIs

Lesson 28 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

Connecting PHP to MySQL: APIs, Drivers & Extensions

1. What is a Database API?

API (Application Programming Interface): A set of rules and protocols that allows one software application to communicate with another. In the PHP-MySQL context, a database API provides the functions and classes PHP needs to talk to a MySQL database server.

Components Involved:

ComponentRole
PHP ScriptYour application code that wants to store/retrieve data
PHP ExtensionMySQLi or PDO — the "translator" between PHP and MySQL
MySQL DriverLow-level C library that actually sends commands to MySQL server
MySQL ServerThe database server process that stores and manages data

2. Two Main PHP Database Extensions

a) MySQLi Extension (MySQL Improved)

  • "i" stands for "Improved" — a major upgrade over the old (deprecated) mysql_ extension.
  • Designed specifically for MySQL databases only.
  • Supports both Procedural style (function-based) and Object-Oriented style (class-based).
  • Supports prepared statements, multiple statements, and transactions.

b) PDO (PHP Data Objects)

  • A Database Abstraction Layer (DAL).
  • Supports 12+ different database types (MySQL, PostgreSQL, SQLite, Oracle, etc.) through swappable drivers.
  • Object-Oriented ONLY — no procedural interface.
  • Makes it easy to switch databases without rewriting your PHP code.

3. MySQLi vs PDO — Comprehensive Comparison

FeatureMySQLiPDO
Database SupportMySQL Only12+ databases (portable)
Programming StyleOOP + ProceduralOOP Only
Prepared StatementsYes (both client & server side)Yes (client side)
Named ParametersNo (uses ? placeholders)Yes (uses :name placeholders)
Error HandlingChecking connect_error propertyExceptions (Try-Catch blocks)
PerformanceSlightly faster for MySQLSlightly slower (abstraction overhead)
When to UseWhen MySQL is the only DB you'll ever useWhen you might switch databases, or want cleaner error handling

4. Connection — Three Approaches

Approach 1: MySQLi Object-Oriented (Recommended for MySQL projects)

<?php
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "myDatabase";

// Create connection (new mysqli is the OOP approach)
$conn = new mysqli($servername, $username, $password, $dbname);

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

Approach 2: MySQLi Procedural

<?php
$conn = mysqli_connect("localhost", "root", "", "myDatabase");

if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected using MySQLi Procedural!";
?>

Approach 3: PDO with Try-Catch

<?php
try {
  $pdo = new PDO("mysql:host=localhost;dbname=myDatabase", "root", "");
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected using PDO!";
} catch (PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>

5. Closing the Connection

Always close the database connection when your script finishes using it. This frees up server resources.

// MySQLi OOP
$conn->close();

// MySQLi Procedural
mysqli_close($conn);

// PDO — simply nullify the object
$pdo = null;

6. Connection Best Practices

  • Never hardcode credentials in your PHP files. Store them in a separate config file and exclude it from version control (add to .gitignore).
  • Always check for connection errors before executing queries.
  • Use prepared statements (covered in CRUD lesson) to prevent SQL Injection.
  • Always close connections after use.