
10-Apr-2009, 11:50
|
 |
Junior Member
|
|
Join Date: Mar 2009
Location: Cyberspace, Earth
Posts: 53
|
|
|
PHP/MySQL Explain Table Script
This script prints out a table similar to what you would see if you ran an explain query using the MySQL command-line interface (minus the borders). Simply set the defined constants to match your database and run the script in your browser. You can change the column widths in the $widths array on line 14.
explain_table.php
PHP Code:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'database');
define('DB_TABLE', 'table');
$db = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL server.');
mysql_select_db(DB_NAME, $db) or die('Could not connect to MySQL database.');
if ($result = mysql_query('EXPLAIN `'.DB_TABLE.'`', $db))
{
echo '<pre>';
$widths = array // Column names and widths (number of spaces)
( 'Field' => 20
, 'Type' => 12
, 'Null' => 4
, 'Key' => 3
, 'Default' => 7
, 'Extra' => 14
);
$margin = 2; // Number of spaces between columns
// Displays column headings
foreach ($widths as $field => $width)
{
/*
* Limits the width of the column. If the contents are wider than the
* column, the full contents can be displayed by hovering the mouse
* over the cell
*/
echo '<span title="'.$field.'">';
if (strlen($field) > $width)
$field = substr($field, 0, $width - 1).'…';
echo '<b>'.str_pad($field, $width + $margin, ' ', STR_PAD_RIGHT).'</b></span>';
}
echo "\n";
// Displays a row for each explained field containing name, type, etc.
while ($row = mysql_fetch_assoc($result))
{
// Displays each column for the current row
foreach ($widths as $field => $width)
{
// Similar to the previous foreach loop
echo '<span title="'.$row[$field].'">';
if (strlen($row[$field]) > $width)
$row[$field] = substr($row[$field], 0, $width - 1).'…';
echo str_pad($row[$field], $width + $margin, ' ', STR_PAD_RIGHT).'</span>';
}
echo "\n";
}
echo '</pre>';
}
else
echo 'Explain query failed.';
?>
Example output
Code:
Field Type Null Key Default Extra
id varchar(8) NO PRI
email varchar(96) NO UNI
username varchar(32) NO UNI
password varchar(32) NO
init_vector varchar(64) NO
last_login_at datetime NO
joined_at datetime NO
|
|