How to connect to a database
Short answer
Create a PDO object. For MySQL the connection string looks like this: mysql:host=localhost;dbname=shop;charset=utf8mb4, followed by the user name and the password. The example uses in-memory SQLite so that it runs without a server:
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
echo $pdo->query('SELECT 1 + 1')->fetchColumn();Output:
2A connection error
If the database is unavailable, PDO throws an exception. Show the visitor a general message and write the details to the log:
<?php
try {
new PDO('sqlite:/no/such/folder/app.db');
echo 'connected';
} catch (PDOException $error) {
echo 'Database is unavailable';
}Output:
Database is unavailableFunctions used in this recipe
- PDO — A database connection.
- PDOStatement — A prepared statement and its result.
- Exception — The base class of exceptions.