PHP+MySQL统计该库中每个表的记录数并按递减顺序排列的方法

这篇文章主要介绍了PHP+MySQL统计该库中每个表的记录数并按递减顺序排列的方法,涉及PHP基于PDO操作MySQL数据库的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了PHP+MySQL统计该库中每个表的记录数并按递减顺序排列的方法。分享给大家供大家参考,具体如下:

这是一段简单的代码,可实现统计该数据库中每个表的记录数,并按递减顺序排列的功能。

  1. $host = '127.0.0.1';
  2. $port = 3306;
  3. $dbname = 'test';
  4. $username = 'root';
  5. $password = '';
  6. function ee($p)
  7. {
  8. if(PHP_SAPI == 'cli')
  9. {
  10. echo "\n";
  11. }else{
  12. echo "<pre>";
  13. }
  14. print_r($p);
  15. if(PHP_SAPI == 'cli')
  16. {
  17. echo "\n";
  18. }else{
  19. echo "<pre>";
  20. }
  21. }
  22. $dsn = "mysql:host={$host};port={$port};dbname={$dbname}";
  23. $opts = array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, PDO::ATTR_AUTOCOMMIT=>0);
  24. try {
  25. $pdo = new PDO($dsn, $username, $password, $opts);
  26. }catch(PDOException $e){
  27. echo $e->getMessage();
  28. }
  29. //有查询结果
  30. function query($sql)
  31. {
  32. global $pdo;
  33. $stmt = $pdo->query($sql);
  34. $data = $stmt->fetchAll(Pdo::FETCH_BOTH);
  35. return $data;
  36. }
  37. //无查询结果
  38. function execute($sql)
  39. {
  40. global $pdo;
  41. $affect_rows = $pdo->query($sql);
  42. return $affect_rows;//影响条数
  43. }
  44. $tables = query("show tables");
  45. $sort_data = array();
  46. foreach($tables as $table)
  47. {
  48. //表记录条数
  49. $count_sql = "select count(*) as num from {$table[0]}";
  50. $stmt = $pdo->query($count_sql);
  51. $info = $stmt->fetch(Pdo::FETCH_BOTH);
  52. $pad_table = str_pad($table[0], 25, ' ');
  53. $sort_data[] = array('table'=>$pad_table, 'num'=>$info['num']);
  54. $sort_index[] = $info['num'];
  55. }
  56. array_multisort($sort_index, SORT_DESC, $sort_data);
  57. foreach($sort_data as $val)
  58. {
  59. $row_str = <<<eof
  60. {$val['table']} [{$val['num']}]
  61. eof;
  62. ee($row_str);
  63. }