All articles

Configure PHP and connected services

Connect PHP to MySQL with PDO and Run a Prepared SELECT

Connect PHP to MySQL with PDO and inspect the rows returned by a prepared SELECT, with a generic error message for database failures.

Editorial illustration for Connect PHP to MySQL and Fetch a Row with PDO or MySQLi

To connect PHP to MySQL and run a prepared SELECT, pass a MySQL DSN and separate credentials to PDO, prepare the SQL, execute it, and inspect the fetched rows. Choose PDO if you want an API that can also work with other database types. MySQLi is the MySQL-only alternative, but this walkthrough uses just one connection path. PDO supports different DBMS, while MySQLi is limited to MySQL.

Choose PDO for this connection

You need a MySQL database, its host, and credentials for an account that can read the table you query. The PHP example below uses a teaching database named example_app. Replace the username and password placeholders with your own values, and change the host or database name if yours differ. Keep real credentials out of a published example.

If you want a small table to follow along with, create and populate this example database in MySQL:

CREATE DATABASE example_app;
USE example_app;

CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

INSERT INTO users (id, name) VALUES (1, 'Ada');

This is example setup, not an assumption that a users table already exists on your server. The PHP query will select from this table without accepting an input value.

Connect with a MySQL DSN and handle connection or query errors

The documented PDO MySQL connection-string format is mysql:host=hostname;dbname=database_name, with the username and password supplied alongside it. The example uses 127.0.0.1 for the host and example_app for the database. Change those values together with the credentials if your database is elsewhere.

The code sets PDO's error mode to PDO::ERRMODE_EXCEPTION. That setting enables PDO to throw exceptions for errors. The catch block prints a generic message rather than printing the exception or the credentials. That distinction matters when you are checking a failed connection: an error message should tell you the operation failed without revealing the password you supplied.

Prepare and execute a fixed SELECT, then inspect the fetched rows

Save the following as a PHP file after replacing the credential placeholders. It uses one fixed query against the example table:

<?php
$host = '127.0.0.1';
$database = 'example_app';
$username = 'REPLACE_WITH_USERNAME';
$password = 'REPLACE_WITH_PASSWORD';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$database",
        $username,
        $password
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $pdo->prepare('SELECT name FROM users WHERE id = 1');
    $statement->execute();
    $rows = $statement->fetchAll();

    var_dump($rows);
} catch (PDOException $error) {
    echo "Database operation failed.\n";
}

Here, the host and database variables build the connection DSN. They are not inserted into the SELECT: the SQL itself is a fixed string with the example ID 1 written into it. The PDO manual describes prepare() as preparing a statement and returning a statement object, execute() as executing that prepared statement, and fetchAll() as fetching the remaining rows from its result set. The final var_dump() displays what was fetched so you can inspect it without relying on a particular fetch mode or array-key layout.

Check the result and know when this example is not enough

With the example table populated, a completed query should give you a displayed result to inspect for the selected name. If a connection or query exception reaches the handler instead, you will see Database operation failed. rather than the fetched result or the credentials. The example does not claim a particular printed array layout, so inspect the displayed value before writing code that reads a specific key.

Do not turn this into an input-driven lookup by interpolating a submitted ID into the SQL string. Accepting an input value calls for a separately documented parameter-binding example; this fixed SELECT does not teach that procedure. Likewise, it does not provide a separate missing-row message. If your next task is to distinguish a missing row from other results, consult the relevant result-fetching documentation before adding that branch.

← All articles