Library contents

PHP PDO::prepare and execute

Bind sale amounts to a prepared insert and ask SQLite to total the stored values.

A simple example

PDO::prepare and execute

  1. Start with Rows containing 2 and 3
  2. Do this Sum the numeric column
  3. Result 5
The database adds the two selected values into one result.

Syntax

PHP syntax
$insert->execute([$amount])
Run these examples in PHP

Save one example at a time as lesson.php. Use PHP 8.2 or later.

php lesson.php

Total sales in a temporary database

A shopkeeper wants a daily sales total from a handful of transaction records. Set up a temporary database, store the sample amounts and let the query aggregate them into the reported figure.

Result16
lesson.php
<?php
$db = new PDO("sqlite::memory:", null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->exec("CREATE TABLE sale (amount INTEGER NOT NULL)");
$insert = $db->prepare("INSERT INTO sale VALUES (?)");
foreach ([3, 8, 5] as $amount) {
    $insert->execute([$amount]);
}
echo $db->query("SELECT SUM(amount) FROM sale")->fetchColumn(), PHP_EOL;
Output
16

Each execution binds a new integer amount. SUM adds the three stored sales.

Advertisements

Total art-room orders

A school enters one quantity per stationery order. Store the batch counts in separate rows and ask the database for their sum. Which total should appear?

GivenRows 3 · 5 · 9
Worked result17

Total returns at two desks

Two library desks log the number of returned kits. Store the batch counts in separate rows and ask the database for their sum. Which total should appear?

GivenRows 8 · 2
Worked result10

What to watch for

This example requires PDO_SQLITE. Its in-memory database lasts for the lifetime of the connection.

Documentation for PDO::prepare and execute