1

How to query mysql data and display it in the form of ascii text table in a Browser, just as you get it in command line. A small example is given below :

+------+---------+---------------------+------------+
| S.No | S.R.NO. | EMPLOYEE NAME       | D.O.B      |
+------+---------+---------------------+------------+
|    1 |       0 | T CHANDRASHEKAR     | 01/01/2000 |
|    2 |  000102 | A RAMESH            | 01/01/2000 |
|    3 |  601026 | B DEEPAK KUMAR      | 01/01/2000 |
|    4 |  543250 | N VIRUPAKSHAIAH     | 02/01/2000 |
|    5 |  610019 | ANAND S GUNDI       | 15/01/2000 |
|    6 |  535035 | ADAM BASHA          | 27/01/2000 |
|    7 |  625893 | A N MOHAN KUMAR     | 06/02/2000 |
|    8 |  547830 | RAJENDRA NAIK       | 07/02/2000 |
|    9 |  698742 | S M SUSHMA          | 19/02/2000 |
|   10 |  655542 | B JAYACHANDRA       | 24/02/2000 |
|   11 |  624769 | B HANUMANTHAPPA     | 25/02/2000 |

It would be better if it is possible using php. Please help.

2
  • 1
    What are you asking? How to get the data from the database or how to output it? If you don't know either then you should probably start by reading a few tutorials. Commented Feb 21, 2016 at 8:28
  • Select * from mytable; gives you the above output in command line. But I want the same format in browser using php code. Normally, you add html table and format the data, but I want it in ascii text table format. Commented Feb 21, 2016 at 8:34

3 Answers 3

3

Approach

This is possible. The main difficulty is the variable nature of the string lengths, which will typically cause the output data to be difficult to read.

To address this, I suggest that you:

  • Find the maximum string length in each column
  • Output Headers with top and lower borders, with header names padded to be same width as maximum cell width
  • Output each row with the cells padded to the target column width.

Code Sample

I'm not able to unit-test the code shown below at present, but it should be ok; post a comment if you have any trouble.

<?php

// Open connection
$mysqli = new mysqli("db_host", "db_user", "db_password", "db_schema");

// Check that connection succeeded
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

// Prepare query
$query = "SELECT * FROM `myTable`";

// Fetch results as associative array
$resultSet = [];
if ($result = $mysqli->query($query)) {

    while ($row = $result->fetch_assoc()) {
        $resultSet[] = $row;
    }

    // Free result set
    $result->free();

    // Close Connection to DB
    $mysqli->close();
} else {

  // Close Connection to DB and print error message
  $mysqli->close();
  die('An error occurred when executing SQL, please check your SQL query.');
}



// If results empty, output error
if (count($resultSet)<1) {
  die('<pre>----NO DATA----'+"\n\n"+'Please revise your query</pre>');
}

// Get column names
$keys = array_keys($resultSet[0]);

// Iterate over column names, get starting widths
$maxLength = [];
foreach ($keys as $column) {
  $maxLength[$column] = mb_strlen($column);
}

// Iterate over result-set, get maximum string length for each column
foreach ($resultSet as $row) {
  foreach ($keys as $column) {

    // If current cell length is greater than column width, increase column width
    if (mb_strlen($row[$column]) > $maxLength[$column]) {
      $maxLength[$column] = mb_strlen($row[$column]);
    }

  }
}

echo '<pre>';

// Output top border
echo '+';
foreach ($keys as $column) {
  echo str_repeat('-', $maxLength[$column]+2);
  echo '+';
}
echo "\n";

// Output header
echo '| ';
foreach ($keys as $column) {
  echo $column.str_repeat(' ', $maxLength[$column] - mb_strlen($column));
  echo ' | ';
}
echo "\n";

// Output bottom border
echo '+';
foreach ($keys as $column) {
  echo str_repeat('-', $maxLength[$column]+2);
  echo '+';
}
echo "\n";

// Output all rows
foreach ($resultSet as $row) {
  echo '| ';
  foreach ($keys as $column) {
    echo $row[$column].str_repeat(' ', $maxLength[$column] - mb_strlen($row[$column]));
    echo ' | ';
  }
echo "\n";
}

echo '</pre>';


?>

NOTE The above code is multi-byte safe but it disregards character width; if the output contains characters of variable width then there might be slight 'kinks' in the column separators. This may be worth a revision if you encounter such problems in the display.

Sign up to request clarification or add additional context in comments.

6 Comments

+------+---------+---------------------+------------+-------------+| 0 | 0 | 0 | 0 | 0 | +------+---------+---------------------+------------+-------------+| Warning: main(): Couldn't fetch mysqli_result in C:\xampp\htdocs\bellary\birthdays.php on line 88 this is what I get
@adam1969in Corrected typos in the code sample, please re-run and let me know how it goes. I'm on the move so still can't test locally.
Superb...! After correcting two more typos in line 71 and 92, it gives out the desired result. But, the beginning '|' is printed only for two lines and then omitted for all other rows. Maybe there is some typo somewhere, I will check it soon. Meanwhile, if you can get it, please convey it. Excellent once again and thank you very much.
@adam1969in move the 'echo' statement after the comment 'output all rows' down one line; I.e. Move inside the first for each loop. I've corrected my answer accordingly.
Perfect @Peter Scott. Excellent and Hats Off. Just correct the typos in line 71 ` a ";" after echo "\n" code and in line 92 ` echo $row[$column]str_repeat ` a "." is missing, it should be ` $row[$column].str_repeat `. Everything works perfect. Thanks a Lot.
|
1

Edit: Looks like it's impossible without writing fancy wrapper scripts to emulate the exact MySQL shell output (such as in @PeterScott's answer). The closest you can get to this probably is dumping the output into a temporary file:

<?php
mysqli_query("select * from mytable into outfile '/tmp/mytable.out'");

and then output this file in a browser, wrapping it in PRE tags:

<?php
$output = file_get_contents('/tmp/mytable.out');
echo '<pre>'. $output .'</pre>';

No way of grabbing this data directly from MySQL console, I'm afraid.

4 Comments

Good one, but the horizontal and vertical lines of table are missing, leading into unformatted table data
@SergeyVidusov See my answer; it seems like some simple string padding makes the output quite easy.
@PeterScott Exactly what I meant by "fancy wrapper scripts" :)
@SergeyVidusov Ah, as you were then.
0
mysql -uroot -p dbname -e 'select * from table_name' -H > dump.php

then you can visit the table content from browser :http://192.168.2.xx/dump.php

-H in mysql command line means output in HTML format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.