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
- Start with Rows containing 2 and 3
- Do this Sum the numeric column
- Result 5
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.phpTotal 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.
<?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;
16
Each execution binds a new integer amount. SUM adds the three stored sales.
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?
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?
What to watch for
This example requires PDO_SQLITE. Its in-memory database lasts for the lifetime of the connection.