Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to select rows from a database

Short answer

Prepare the query, run it and fetch the rows with fetchAll():

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, title TEXT, price INTEGER)');
$pdo->exec("INSERT INTO products (title, price) VALUES ('Tea', 250), ('Coffee', 400), ('Juice', 180)");
 
$statement = $pdo->prepare('SELECT title FROM products WHERE price < ? ORDER BY title');
$statement->execute([300]);
 
echo implode(', ', $statement->fetchAll(PDO::FETCH_COLUMN));

Output:

Juice, Tea

A single row

fetch() returns a row, or false if nothing was found:

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, title TEXT, price INTEGER)');
$pdo->exec("INSERT INTO products (title, price) VALUES ('Tea', 250)");
 
$statement = $pdo->prepare('SELECT title, price FROM products WHERE id = ?');
$statement->execute([1]);
$product = $statement->fetch(PDO::FETCH_ASSOC);
 
echo $product ? $product['title'] . ' ' . $product['price'] : 'not found';

Output:

Tea 250

Functions used in this recipe

  • PDOStatement — A prepared statement and its result.
  • PDO — A database connection.
  • array_column — Pulls the values of one key out of an array of arrays.

Thanks for reading!

Donate to the site — we work hard for you.