This worked for me, although creating an object is not required.
<?php
namespace yourNameSpace;
// Extend PDO class for safe error handling
Class SafePDO extends \PDO {
public static function exception_handler($exception) {
// Output the exception details
die("Uncaught exception: " . $exception->getMessage());
}
public function __construct($dsn, $username='', $password='', $driver_options=array()) {
// Temporarily change the PHP exception handler while we . . .
set_exception_handler(array(__CLASS__, 'exception_handler'));
// . . . create a PDO object
parent::__construct($dsn, $username, $password, $driver_options);
// Change the exception handler back to whatever it was before
restore_exception_handler();
}
}
class TableRows extends \RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
trait traitSQLExecution {
private function generateTable(
$sql,
$servername = "default_value",
$username = "default_value",
$password = "default_value",
$dbname = "default_value"
) {
// Connect to the database with defined constants
$pdo = new SafePDO("mysql: host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try {
$stmt = $pdo->prepare($sql);
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(\PDO::FETCH_ASSOC);
$recordSet = $stmt->fetchAll();
echo '<table id="myReport"><tr>';
// Get table headers dynamically
foreach($recordSet[0] as $k=>$v) {
echo "<th>$k</th>";
}
echo '</tr>';
foreach(new TableRows(new \RecursiveArrayIterator($recordSet)) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$pdo = null;
$stmt = null;
echo '</table>';
}
}
class obj_report {
// use section is used to include reusable pieces of code
use traitSQLExecution;
// Construct is called upon instantiation of an object
function __construct($table){
/****************************************************************************************
* Do not include public variables as this is bad design.
* Only public methods should be available to change the object in a predictable fashion.
****************************************************************************************/
if ( $table !== "" ) {
$this->generateTable($table);
}
}
}
$obj = new obj_report((string)htmlspecialchars($_POST['table']) ?: "");
$obj = NULL;
?>