Advertisement
Guest User

Untitled

a guest
Jan 20th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. #!/usr/bin/env php
  2. <?php
  3. if(!defined("STDIN")) define("STDIN", fopen("php://stdin", "R"));
  4.  
  5. $host = "localhost";
  6. $user = "root";
  7. $password = "";
  8. $schema = "";
  9.  
  10. $opts = getopt("h:u:p:s:");
  11. if(isset($opts["h"])) $host = $opts["h"];
  12. if(isset($opts["u"])) $user = $opts["u"];
  13. if(isset($opts["p"])) $password = $opts["p"];
  14. if(isset($opts["s"])) $schema = $opts["s"];
  15.  
  16. $db = @new mysqli($host, $user, $password, $schema);
  17. if(isset($db->conenct_error)) die($db->connect_error);
  18.  
  19. echo "Connected!", PHP_EOL;
  20.  
  21. while(true){
  22. echo "> ";
  23. $line = rtrim(trim(fgets(STDIN)), ";");
  24. if($line === "exit") break;
  25. $start = microtime(true);
  26. $result = $db->query($line);
  27. $end = microtime(true);
  28. if($result === false){
  29. echo "Error: $db->error", PHP_EOL;
  30. }elseif($result instanceof mysqli_result){
  31. $cols = [];
  32. $rows = 0;
  33. while(is_array($row = $result->fetch_assoc())){
  34. foreach($row as $k => $v){
  35. if(!isset($cols[$k])) $cols[$k] = [$k];
  36. $cols[$k][] = $v;
  37. }
  38. $rows++;
  39. }
  40. $result->close();
  41. if($rows === 0){
  42. echo "Empty result set ";
  43. }else{
  44. $paddings = [];
  45. foreach($cols as $k => $v){
  46. $paddings[$k] = max(array_map("strlen", $v));
  47. }
  48. $len = array_sum($paddings) + 1 + count($cols) * 3;
  49. for($i = 0; $i <= $rows; $i++){
  50. if($i === 0) echo str_repeat("=", $len), PHP_EOL;
  51. foreach($cols as $k => $v){
  52. echo "| " . str_pad($v[$i], $paddings[$k], " ", STR_PAD_BOTH) . " ";
  53. }
  54. echo "|", PHP_EOL;
  55. if($i === 0) echo str_repeat("=", $len), PHP_EOL;
  56. }
  57. echo str_repeat("=", $len), PHP_EOL;
  58. echo ($rows === 1 ? "1 row" : "$rows rows") . " in result set ";
  59. }
  60. }elseif(strtoupper(substr($line, 0, 6)) === "INSERT" and isset($db->insert_id)){
  61. echo "Insert ID: $db->insert_id", PHP_EOL;
  62. }else{
  63. echo "Query success ";
  64. }
  65. echo "(Query completed in " . round($end - $start, 4) . " second", $end - $start > 1 ? "s" : "", ")", PHP_EOL;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement