#!/usr/bin/php getAttribute(PDO::ATTR_DRIVER_NAME) . "\n"; echo "Client version: " . $db->getAttribute(PDO::ATTR_CLIENT_VERSION) . "\n"; echo "Server version: " . $db->getAttribute(PDO::ATTR_SERVER_VERSION) . "\n"; } if (isset($argv[1])){ if (getenv('PDOCONSOLE_NO_RLWRAP') === false){ /* try to run in rlwrap to get readline features */ $paths = explode(':', $_ENV['PATH']); $paths[] = '.'; foreach ($paths as $path){ @pcntl_exec("$path/rlwrap", array_merge($RLWRAP_ARGS, array(PHP_BINDIR . '/php', $argv[0], $argv[1])), array_merge($_ENV, array('PDOCONSOLE_NO_RLWRAP' => 'true')) ); } } $db = new PDO($argv[1]); } else { die("usage: $argv[0] connection-string\n"); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); printver($db); while (1){ /* print prompt and get response */ echo 'PDO> '; $line = fgets(STDIN); if ($line === false){ echo "\n"; break; } /* get rid of trailing/leading spaces/newlines*/ $line = trim($line); /* ignore blank lines */ if ($line == '') continue; /* handle .exit/.q and .v */ if ($line{0} == '.'){ $lparts = explode(' ', $line); if ($lparts[0] == '.exit' || $lparts[0] == '.q'){ echo "\n"; break; } if ($lparts[0] == '.v'){ printver($db); continue; } } /* pass query to database */ $sth = $db->query($line); /* check for error */ if (!$sth){ /* print error information*/ $ei = $db->errorInfo(); echo "SQLSTATE: $ei[0] Err: $ei[1] "; echo outquote($ei[2]); echo "\n"; } else { /* attempt to fetch all rows */ $sth->setFetchMode(PDO::FETCH_ASSOC); $rows = $sth->fetchAll(); /* if the query returned rows, display them */ if ($rows){ /* this is a bit inefficient because we need to iterate over the * entire result array twice. But to print a pretty table we need to * figure out in advance the width of each column */ /* get field names */ $keys = array_keys($rows[0]); /* get widths of the field names (minimum widths for columns) */ $widths = array_combine($keys, array_map('strlen', $keys)); /* see if we need to make any columns wider */ foreach ($rows as $row){ foreach ($row as $k=>$v){ $widths[$k] = max($widths[$k], strlen($v)); } } /* generate a header with column names and a divider */ $header = '|'; $divider = '+'; foreach ($widths as $k => $w){ $header .= str_pad($k, $w) . '|'; $divider .= str_pad('', $w, '-') . '+'; } /* print out the header */ echo "$divider\n$header\n$divider\n"; /* print out the result rows */ foreach ($rows as $row){ echo '|'; foreach ($row as $k => $v){ if (is_numeric($v)) echo str_pad($v, $widths[$k], ' ', STR_PAD_LEFT); else echo str_pad($v, $widths[$k], ' ', STR_PAD_RIGHT); echo '|'; } echo "\n"; } /* and the bottom border of the table */ echo "$divider\n"; } else { /* query didn't return any rows. display a number that may or may * not have something to do with the number of rows affected by the * query */ echo $sth->rowCount() . " rows affected (maybe)\n"; } } } ?>