PHP interacts with databases using various extensions and libraries that facilitate communication between PHP scripts and database management systems (DBMS). The most common way to interact with databases in PHP is through the following methods:
-
MySQLi (MySQL Improved):
- A PHP extension that provides an interface to interact with MySQL databases.
- Supports both procedural and object-oriented programming styles.
- Example of connecting to a MySQL database using MySQLi:
$mysqli = new mysqli("localhost", "username", "password", "database"); // Check connection if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); }
-
PDO (PHP Data Objects):
- A database access layer providing a uniform method of access to multiple databases.
- Supports prepared statements, which help prevent SQL injection attacks.
- Example of connecting to a database using PDO:
try { $pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password"); // Set the PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
-
Executing Queries:
-
After establishing a connection, you can execute SQL queries to retrieve or manipulate data.
-
Example of executing a query using MySQLi:
$result = $mysqli->query("SELECT * FROM users"); while ($row = $result->fetch_assoc()) { echo $row['username']; } -
Example of executing a query using PDO:
$stmt = $pdo->query("SELECT * FROM users"); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['username']; }
-
These methods allow PHP to perform various database operations such as creating, reading, updating, and deleting records (CRUD operations).
