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:
- Hostname: Usually
localhost. - Username: Default is often
root. - Password: Default is often empty (
''). - 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:
- MySQLi: (MySQL Improved) - Specific to MySQL.
- 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(); } ?>