1

It is fairly easy to use PHP to generate HTML code to display a table (which is an array of arrays of equal length), for instance the code below. I was wondering however: is there a PHP function that does this for you? I searched Google on print table in php and searched the PHP manual on table, but could not find such a function.

Code from http://davidwalsh.name/html-mysql-php to print a table:

$result2 = mysql_query('SHOW COLUMNS FROM '.$table) or die('cannot show columns from '.$table);
if(mysql_num_rows($result2)) {
    echo '<table cellpadding="0" cellspacing="0" class="db-table">';
    echo '<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default<th>Extra</th></tr>';
    while($row2 = mysql_fetch_row($result2)) {
        echo '<tr>';
        foreach($row2 as $key=>$value) {
            echo '<td>',$value,'</td>';
        }
        echo '</tr>';
    }
    echo '</table><br />';
}
2
  • 3
    i doubt it. Probably you have to create your own function Commented Jan 22, 2015 at 16:14
  • 5
    PHP is a toolkit. Some of the tools (functions) are more like swiss army knives and can do multiple things, but there's no function that'll generate a table for you. That'd be like "build_a_house()" and expecting it to know exactly what KIND of house you want. Commented Jan 22, 2015 at 16:17

2 Answers 2

1

Answer to your question: No, there isn't.

However, I did find the idea interesting so I've written a function that does just that. However, your example uses MySQL() which is deprecated and insecure. So I'll be using a PDO class instead.

Please keep in mind that this function is only usefull for printing out a database table. It's NOT secure against injection and therefor should NEVER be used with user input inside the query!

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "pdo.class.php";

//Database data
define("DB_HOST", "localhost");
define("DB_USER", "");
define("DB_PASS", "");
define("DB_NAME", "");

function printTable($tbl_name, $db_query){
    //New PDO object
    $pdo = new Database();

    //Get column names
    $pdo->query("DESCRIBE ". $tbl_name);
    $col_names = $pdo->column();

    //Get number of columns
    $col_cnt = count($col_names);

    //Setup table - user css class db-table for design
    echo "<table class='db-table'>";
    echo "<tr colspan='". $col_cnt ."'>". $tbl_name ."</tr>";
    echo "<tr>";

    //Give each table column same name is db column name
    for($i=0;$i<$col_cnt;$i++){
        echo "<td>". $col_names[$i] ."</td>";
    }

    echo "</tr>";

    //Get db table data
    $pdo->query($db_query);

    $results = $pdo->resultset();
    $res_cnt = count($results);

    //Print out db table data
    for($i=0;$i<$res_cnt;$i++){
        echo "<tr>";
        for($y=0;$y<$col_cnt;$y++){
            echo "<td>". $results[$i][$col_names[$y]] ."</td>";
        }
        echo "</tr>";
    }
}

//Query
$sqlq = "SELECT * FROM tablename";

//Useage: printTable("tablename","query");
printTable("tablename",$sqlq);

?>

The PDO class itself:

Class Database{
    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;

    private $dbh;
    private $error;

    private $stmt;

    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }

    public function query($query){
        $this->stmt = $this->dbh->prepare($query);
    }

    public function bind($param, $value, $type = null){
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($param, $value, $type);
    }

    public function execute(){
        return $this->stmt->execute();
    }

    public function column(){
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    public function resultset(){
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function single(){
        $this->execute();
        return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function rowCount(){
        return $this->stmt->rowCount();
    }

    public function lastInsertId(){
        return $this->dbh->lastInsertId();
    }

    public function beginTransaction(){
        return $this->dbh->beginTransaction();
    }

    public function endTransaction(){
        return $this->dbh->commit();
    }

    public function cancelTransaction(){
        return $this->dbh->rollBack();
    }

    public function debugDumpParams(){
        return $this->stmt->debugDumpParams();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-1

There is no such built-in function. You created your own, that's how it works. There is always var_dump(), but that is not readable to your average visitor.

7 Comments

This is a comment not an answer
If the desired function does not exist, then "No" is a valid a valid answer.
I'm not allowed to comment because I didn't earn enough reputation. It is allowed at 50 rep. but if i get downvotes for providing correct statements about asked questions, it will take a lot longer to gain those reputation. So I'm technically forced to answer instead of commenting such questions.
@Leigh Just playing devil's advocate here but doesn't that mean the question itself is not constructive and should be closed? This is about as trivial as they come in terms of Google searching. The PHP docs are very well laid out. I see what you mean by saying if the question is yes/no, then no is an answer, but it seems like answering questions like this should be discouraged as they are not constructive and don't fit the proper Q&A format of this site. Like I said, just asking for my learning benefit. I won't downvote this post.
@War10ck - doesn't that mean the question itself is not constructive... No, the question alone determines that, not the answers ;) PHP is not my area, so the issue of whether this specific "question" is constructive is best left up to folks familiar with the language (BTW, if that is you - you should vote to close if you feel it is off topic)...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.