Retrieve data from mysql and display in the form of ascii text table in browser

安稳与你 提交于 2021-01-01 08:38:11

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/35533854/retrieve-data-from-mysql-and-display-in-the-form-of-ascii-text-table-in-browser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!