Connect to a Database in PHP With PDO and Prepared Statements
Almost every useful PHP application stores data: users, products, orders, posts, and form submissions all live in a database, most often MySQL or MariaDB on typical hosting. PHP offers several ways to talk to that database, and PDO, short for PHP Data Objects, is the one worth learning first. It works with multiple database systems through a consistent interface, and it makes the safest way of running queries, prepared statements, the natural way.
This guide covers the complete everyday workflow: building the connection string, connecting with sensible error settings, running SELECT queries and fetching results, and performing INSERT, UPDATE, and DELETE operations, all with php pdo prepared statements so that values from visitors can never break out of a query and change its meaning. If your data arrives through a form, read this together with the PHP form handling guide, because validated form input and prepared statements are the two halves of safe data storage.
Why PDO and Why Prepared Statements Matter
The danger PDO protects against is SQL injection. If a query is built by pasting user input directly into an SQL string, a crafted input can close the intended value early and add its own SQL, potentially reading or destroying data. Prepared statements remove that risk by design. The SQL structure is sent to the database first, with placeholders where values belong. The values are sent separately afterwards, and the database treats them strictly as data, never as part of the command.
PDO also separates your code from one specific database extension, so moving to another supported system mostly means changing the connection string rather than rewriting every query.
Connecting to the Database
A PDO connection needs a DSN, a data source name string that names the driver, host, database, and character set, plus the database username and password. You create the connection once, usually at the top of a shared include file, and reuse the resulting object throughout the script.
<?php
$dsn = "mysql:host=localhost;dbname=shop;charset=utf8mb4";
$username = "db_user";
$password = "db_password";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log($e->getMessage());
die("Database connection failed.");
}
?>
The DSN begins with mysql: to select the MySQL driver, then gives the host, the database name after dbname, and the utf8mb4 character set, which supports the full range of modern characters including emoji. The try and catch structure handles connection failure gracefully: PDO throws a PDOException when something goes wrong, and catching it lets you log the real error privately while showing the visitor a generic message. Never print the raw exception to the page, because connection errors can reveal hostnames, usernames, and other details an attacker would enjoy.
The two setAttribute lines configure behaviour. ERRMODE_EXCEPTION makes query errors throw exceptions too, so failures are caught and handled rather than silently ignored. FETCH_ASSOC sets the default result format to associative arrays keyed by column name, which is the most readable format for everyday work. In real projects the credentials live outside the public web folder or in environment configuration, never committed to a public code repository, and each application gets its own database user with only the permissions it needs.
SELECT Queries and Fetching Results
Reading data is the most common operation. When a query has no user supplied values, you can run it directly with the query method. As soon as a value from outside the code takes part, switch to a prepared statement, even for a simple lookup by ID.
<?php
$stmt = $pdo->query("SELECT id, name, price FROM products ORDER BY name");
$products = $stmt->fetchAll();
foreach ($products as $product) {
echo htmlspecialchars($product["name"]) . " - " . $product["price"] . "<br>";
}
?>
The query method runs the SQL and returns a statement object. Calling fetchAll retrieves every row at once as an array of associative arrays, thanks to the default fetch mode set at connection time. The loop then prints each product, escaping the name with htmlspecialchars because data read from a database is still untrusted output when displayed; it may have come from a user originally. For very large result sets, fetching row by row inside a while loop with fetch uses less memory than loading everything at once.
<?php
$stmt = $pdo->prepare("SELECT id, name, price FROM products WHERE id = ?");
$stmt->execute([$productId]);
$product = $stmt->fetch();
if ($product) {
echo htmlspecialchars($product["name"]);
} else {
echo "Product not found.";
}
?>
This is the prepared statement pattern in its simplest form. Prepare sends the SQL with a question mark placeholder where the ID belongs. Execute supplies the actual value in an array, and the database binds it safely as data. The fetch method returns a single row, or false when nothing matched, which the if check handles cleanly. Notice that even a numeric ID goes through a placeholder. Making prepared statements the default for every value keeps the habit unbreakable, which is exactly the point; the one time a value is pasted into a string is the one time it can be exploited. For the SQL side of these queries, the examples in the SQL SELECT queries guide show how to shape the statements themselves.
Named Placeholders for Readable Queries
Question mark placeholders work well for one or two values. As queries grow, keeping track of which position belongs to which value becomes error prone. Named placeholders solve that by giving each placeholder a label starting with a colon, and passing an associative array to execute.
<?php
$stmt = $pdo->prepare(
"SELECT id, name FROM users WHERE role = :role AND active = :active"
);
$stmt->execute([
"role" => "editor",
"active" => 1
]);
$editors = $stmt->fetchAll();
?>
The SQL names its placeholders :role and :active, and the array passed to execute maps matching keys to values. Reading the code later, there is no counting of positions; each value is labelled. Named and positional placeholders should not be mixed in the same statement, so choose one style per query. Many developers use named placeholders as their default because queries in real applications tend to grow more columns over time, and labelled values stay clear as they grow.
Prepared statements can also be reused. Preparing once and executing repeatedly with different values is efficient for batch work, such as importing many rows, because the database parses the SQL a single time. That pattern appears in the insert section next, where the same statement can add record after record.
INSERT, UPDATE, and DELETE
Writing operations follow the identical prepare and execute rhythm. The only differences are the SQL verbs and how you confirm the result: the rowCount method reports how many rows a statement changed, and lastInsertId returns the auto generated ID of a newly inserted row.
<?php
$stmt = $pdo->prepare(
"INSERT INTO products (name, price) VALUES (:name, :price)"
);
$stmt->execute([
"name" => "Notebook",
"price" => 4.50
]);
$newId = $pdo->lastInsertId();
echo "Created product " . $newId;
?>
The INSERT statement lists the columns and uses named placeholders for the values. After executing, lastInsertId, called on the connection object rather than the statement, gives the ID the database assigned to the new row, which is useful when the next step needs to reference that record, for example to add related rows or to redirect to its edit page. Values in the execute array can come straight from validated form fields: validate first, then bind and store.
<?php
$stmt = $pdo->prepare(
"UPDATE products SET price = :price WHERE id = :id"
);
$stmt->execute([
"price" => 5.25,
"id" => 12
]);
echo $stmt->rowCount(); // rows actually updated
?>
The UPDATE changes the price for the row matching the ID in its WHERE clause. Always pause on the WHERE clause in updates and deletes: without it, the statement applies to every row in the table. The rowCount result tells you whether the expected row was found and changed, which your code can check before reporting success to the user.
<?php
$stmt = $pdo->prepare("DELETE FROM products WHERE id = :id");
$stmt->execute(["id" => 12]);
echo $stmt->rowCount(); // 1 if a row was deleted
?>
DELETE uses the same shape again. In many real systems a hard delete is replaced by a soft delete, setting an archived flag column with an UPDATE instead, so records can be recovered or audited later. Whichever approach a project chooses, the mechanics remain prepared statements with bound values, and the broader SQL patterns behind these statements are collected in the SQL insert, update and delete guide.
Searching With LIKE and Handling IN Lists
Two situations deserve special notes because they tempt developers back into string building. The first is a LIKE search, where the value contains wildcard characters. The wildcards belong in the bound value, not in the SQL string.
<?php
$term = "note";
$stmt = $pdo->prepare("SELECT id, name FROM products WHERE name LIKE :term");
$stmt->execute(["term" => "%" . $term . "%"]);
$results = $stmt->fetchAll();
?>
The percent signs, which mean any characters in a LIKE pattern, are added to the value before binding, so the search finds names containing the term. The placeholder still protects the query structure, and the user’s text remains data. For stricter searching you would also escape any percent or underscore characters inside the user’s own term, but the binding approach shown here is the correct foundation.
The second situation is an IN list with a variable number of values. Placeholders cannot bind a whole array as one value, so generate one question mark per item with implode and array_fill, prepare a query containing only those placeholders, and execute with the ID array. The placeholders string contains no user data, and you should check the array is not empty first, because an empty IN list produces invalid SQL.
Transactions for Multi-Step Changes
Some operations must succeed or fail as a unit, like moving money between accounts or creating an order plus its line items. Transactions provide that guarantee: begin, run the statements, then commit to keep the changes or roll back to undo them all if anything throws an error.
<?php
try {
$pdo->beginTransaction();
$pdo->prepare("UPDATE accounts SET balance = balance - 100 WHERE id = ?")
->execute([1]);
$pdo->prepare("UPDATE accounts SET balance = balance + 100 WHERE id = ?")
->execute([2]);
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
error_log($e->getMessage());
}
?>
Both updates run inside the transaction. If the second one fails, the catch block rolls everything back, so the first account is not left debited without the credit arriving. This all or nothing behaviour is essential for data integrity, and combined with ERRMODE_EXCEPTION it is straightforward to implement, because any failure automatically lands in the catch block where the rollback happens. Note the chained prepare and execute calls here, which work because prepare returns the statement; in code you maintain long term, spelling the steps out on separate lines is often clearer.
Put the connection code in one shared file, keep queries close to the features that use them, and let prepared statements be the default everywhere, including admin tools next to features like custom post types in WordPress projects.
Conclusion
PDO gives PHP a clean, consistent way to work with databases, and prepared statements make that work safe by keeping values separate from SQL structure. Connect once with exceptions turned on, prepare every query that involves a value, bind with positional or named placeholders, and use transactions when several changes belong together. Follow those habits and php pdo prepared statements will protect your data while keeping your database code short and readable.
Tagged: php database queries php mysql connection php pdo fetch php pdo prepared statements php snippets sql injection prevention



2 thoughts on “Connect to a Database in PHP With PDO and Prepared Statements”