Search text in fields in every table of a MySQL database

前端 未结 24 1922
梦谈多话
梦谈多话 2020-11-22 06:23

I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:

SELECT * FROM * WHERE * LIKE \'%stuff%\'
         


        
24条回答
  •  执念已碎
    2020-11-22 06:42

    I modified the PHP answer of Olivier a bit to:

    • print out the results in which the string was found
    • omit tables without results
    • also show output if column names match the search input
    • show total number of results

      function searchAllDB($search){
          global $mysqli;
      
          $out = "";
          $total = 0;
          $sql = "SHOW TABLES";
          $rs = $mysqli->query($sql);
          if($rs->num_rows > 0){
              while($r = $rs->fetch_array()){
                  $table = $r[0];
                  $sql_search = "select * from ".$table." where ";
                  $sql_search_fields = Array();
                  $sql2 = "SHOW COLUMNS FROM ".$table;
                  $rs2 = $mysqli->query($sql2);
                  if($rs2->num_rows > 0){
                      while($r2 = $rs2->fetch_array()){
                          $colum = $r2[0];
                          $sql_search_fields[] = $colum." like('%".$search."%')";
                          if(strpos($colum,$search))
                          {
                              echo "FIELD NAME: ".$colum."\n";
                          }
                      }
                      $rs2->close();
                  }
                  $sql_search .= implode(" OR ", $sql_search_fields);
                  $rs3 = $mysqli->query($sql_search);
                  if($rs3 && $rs3->num_rows > 0)
                  {
                      $out .= $table.": ".$rs3->num_rows."\n";
                      if($rs3->num_rows > 0){
                          $total += $rs3->num_rows;
                          $out.= print_r($rs3->fetch_all(),1);
                          $rs3->close();
                      }
                  }
              }
              $out .= "\n\nTotal results:".$total;
              $rs->close();
          }
          return $out;
      }
      

提交回复
热议问题