Skip to content

Instantly share code, notes, and snippets.

@tamouse
Created October 20, 2012 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamouse/3922192 to your computer and use it in GitHub Desktop.
Save tamouse/3922192 to your computer and use it in GitHub Desktop.
Quick 3 column table using PDO
<?php
/**
* quick 3 column table demo using PDO
*/
/* set error reporting for example -- omit in deployed application */
error_reporting(-1);
ini_set('display_errors',true);
ini_set('display_startup_errors',true);
$title = "Testing Quick 3 Column Table using PDO";
$tablename = "threecolumns";
/* connect to the data base -- use real DSN */
try {
$db = new PDO("sqlite::memory:");
}
catch (PDOException $e) {
die("Error making connection: ".$e->getMessage());
}
/* build the data for the example -- omit in real application */
if (false === $db->exec("CREATE TABLE IF NOT EXISTS $tablename (item1 text, item2 text, item3 text)"))
die("no create ".print_r($db->errorInfo(),true));
for ($i=1; $i < 20; $i++) {
if (false === $db->exec("INSERT INTO $tablename (item1, item2, item3) VALUES ('a$i','b$i','c$i')"))
die("no insert ".print_r($db->errorInfo(),true));
}
/* gather the data */
if (false ===
($result = $db->query("SELECT * FROM $tablename"))
)
die("no result ".print_r($db->errorInfo(),true));
if (false ===
($table = $result->fetchAll())
)
die("no table: ".print_r($db->errorInfo(),true));
/* debug echo "<pre>"; var_dump($table); echo "</pre>\n"; */
/* format the data */
include('pagebegin.php'); // all the regular stuff you need to set up the html page
echo "<table width='100%' border='1' colspacing='3px' colpadding='3px'>\n"; // style as appropriate
echo "<thead><td>Column 1</td><td>Column 2</td><td>Column 3</td></thead>\n";
foreach ($table as $row) {
echo "<tr>";
for ($i=0; $i < 3; $i++) {
echo "<td>".$row[$i]."</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
include('pageend.php'); // all the stuff to close out the html page
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" >
</head>
<body>
<h1><?php echo $title; ?></h1>
<!-- page content begins here -->
<!-- page content ends above this line -->
</body> </html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment