PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
CREATE TABLE table1 ( id INT UNSIGNED AUTO_INCREMENT, type INT NOT NULL, PRIMARY KEY (id) ); CREATE INDEX my_idx ON table1 (type); INSERT INTO table1 (type) VALUES (1), (1), (1), (2), (2), (3);
Copy Clear
Copy Format Clear
<?php use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use JetBrains\PhpStorm\ExpectedValues; use PDO; use PDOException; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Helper\TableStyle; use Symfony\Component\Console\Output\BufferedOutput; $view = 'SELECT type from table1 UNION ALL SELECT type from table1'; $query = "EXPLAIN SELECT * FROM ($view) as v WHERE type = ?;"; $type = 2; $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $stmt = $pdo->prepare($query); $stmt->bindParam(1, $type, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); echo createTable($result); function createTable($array) { // Get the headers (keys of the first element) $headers = array_keys($array[0]); // Calculate column widths $columnWidths = []; foreach ($headers as $header) { $columnWidths[$header] = strlen($header); } foreach ($array as $row) { foreach ($row as $key => $value) { $columnWidths[$key] = max($columnWidths[$key], strlen((string) $value)); } } // Build the table $divider = '+'; $headerRow = '|'; foreach ($headers as $header) { $divider .= str_repeat('-', $columnWidths[$header] + 2) . '+'; $headerRow .= ' ' . str_pad($header, $columnWidths[$header]) . ' |'; } $table = $divider . "\n" . $headerRow . "\n" . $divider . "\n"; foreach ($array as $row) { $rowLine = '|'; foreach ($headers as $header) { $rowLine .= ' ' . str_pad((string) $row[$header], $columnWidths[$header]) . ' |'; } $table .= $rowLine . "\n"; } $table .= $divider; return $table; }
Show:  
Copy Clear