Select Data With PDO (+ Prepared Statements)
Menu Select With PDO (+ Prep'd Statem's)
 

Select Data With PDO (+ Prepared Statements)

This example is from the W3C page https://www.w3schools.com/php/php_mysql_select.asp - PHP MySQL Select Data.

The code shows a number of techniques inluding how to dynamically build an HTML table, populating the table with data from a mySQL table.

There lots of advanced PHP class and PDO coding involved here and I have a lot to learn

While the example seems to work I am not sure that if it will work for me. Mainly because I don't understand it.

- needs to be run from the server and this page has tracking.

The PHP file seems to work! The connection credentials are for my database on my webserver. The code shown below has the values from the W3C example.

Top

The Example

Saved as demo_db_select_pdo.php

In this case the database is: myDBPDO and the table is myGuests (The database in the other examples is myDB)

The Code:

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>"; }
function beginChildren() { echo "<tr>"; }

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

The Predefined Constants here are:

  • self::LEAVES_ONLY - an argument of the__construct function

Site design by Tempusfugit Web Design -