Skip to content

Instantly share code, notes, and snippets.

@waelio
Last active December 29, 2015 13:12
Show Gist options
  • Save waelio/a9328a8d684f3a39775c to your computer and use it in GitHub Desktop.
Save waelio/a9328a8d684f3a39775c to your computer and use it in GitHub Desktop.
Create HTML Table (header/body/footer) from MySQL Database using PDO
<?php
function getConnection1(){
$dbhost = "localhost";
$dbuser = "test";
$dbpass = "test";
$dbname = "schema name";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function retun_html_from_mysql(){
$sql_head = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'schemaname' AND TABLE_NAME = 'table_name';";
$sql_body = "select * from table_name;";
try {
$db = getConnection1();
$stmt_head = $db->query($sql_head);
$stmt_body = $db->query($sql_body);
$colcount_head = $stmt_head->columnCount();
$colcount_body = $stmt_body->columnCount();
$db = null;
$data = "<div style='clear: both;'></div>";
$data .= "<table>";
$data .= " <thead>";
$data .= " <tr>";
while ($row = $stmt_head->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
for ($i=0;$i<$colcount_head;$i++){
$data .= "<th>$row[$i]</th>";
}
}
$data .= " </tr>";
$data .= " </thead>";
$data .= " <tbody>";
while ($row = $stmt_body->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data .= "<tr>";
for ($i=0;$i<$colcount_body;$i++){
$data .= "<td>$row[$i]</td>";
}
$data .= "</tr>";
}
$data .= " </tbody>";
$data .= " <tfoot>";
$data .= " <tr>";
for ($i=0; $i<$colcount_head;$i++){
$data .= "<th></th>";
}
$data .= " </tr>";
$data .= " </tfoot>";
$data .= "</table>";
echo $data;
} catch (PDOException $e) {
echo '{"error":{"text":' . $e->getMessage() . '}}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment