Back to course

Connecting PHP to Databases (Introduction to MySQL)

PHP: The Complete 0 to Hero Bootcamp

43. Connecting PHP to Databases (Introduction to MySQL)

Dynamic websites require persistent data storage, which is handled by a database management system (DBMS) like MySQL or MariaDB. PHP acts as the intermediary between the web application and the database.

Relational Databases (RDBMS)

  • Data is stored in structured tables (like Excel sheets).
  • Data manipulation uses Structured Query Language (SQL).
  • MySQL is the standard database bundled with XAMPP/MAMP.

Database Connection Requirements

To connect, PHP needs four pieces of information:

  1. Hostname: Usually localhost.
  2. Username: Default is often root.
  3. Password: Default is often empty ('').
  4. Database Name: The specific database you want to access.

PHP Database Extensions

Historically, PHP used mysql_. This is now deprecated.

Today, we use modern, secure extensions:

  1. MySQLi: (MySQL Improved) - Specific to MySQL.
  2. PDO: (PHP Data Objects) - A database access layer providing a consistent interface for many different databases (MySQL, PostgreSQL, etc.). This is the recommended standard for all modern development.

Initial Connection Setup (Conceptual, using PDO)

php

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Successfully connected to the database."; } catch (PDOException $e) { // Handle connection errors gracefully echo "Connection failed: " . $e->getMessage(); die(); } ?>