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.
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.