This tutorial will guide you to connect your PHP application to a MySQL database using the PHP Data Objects (PDO) interface. PDO is a database access layer providing a uniform method of access to multiple databases.
By the end of this tutorial, you will be able to:
Prerequisites:
* Basic understanding of PHP and MySQL
* PHP and MySQL installed on your machine
* A MySQL database to connect to
PDO provides a consistent interface for accessing databases in PHP. It supports 12 different database systems, of which MySQL is one. PDO is secure and provides an easy way to handle errors.
To connect to a MySQL database with PDO, you need to instantiate the PDO class. The constructor takes four parameters: DSN (data source name), username, password, and an optional array of driver-specific connection options.
The DSN for MySQL takes the following form:
mysql:host=hostname;dbname=databasename
Here is a basic example of a PDO connection:
<?php
$host = 'localhost';
$db = 'testdb';
$user = 'testuser';
$pass = 'testpass';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
?>
Here is an example of running a SELECT query with PDO:
<?php
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch())
{
echo $row['name'] . "\n";
}
?>
This code will output the name of every user in the "users" table.
You can also use PDO to insert data into the database:
<?php
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['name' => 'John', 'email' => 'john@example.com']);
?>
This code will insert a new row into the "users" table.
We've learned how to use PDO to connect to a MySQL database from a PHP application. We've also seen how to execute SELECT and INSERT queries.
Next, you could learn more about PDO's capabilities, such as updating and deleting data, preparing statements, and handling errors.
Additional resources:
* PHP Documentation on PDO
* PHP The Right Way - Databases
Solutions will vary based on your specific database schema. Remember to use prepared statements to protect against SQL injection attacks. Practice with different SQL queries to get a feel for how PDO works.