Search text in fields in every table of a MySQL database

前端 未结 24 1583
梦谈多话
梦谈多话 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:51

    PHP function:

    function searchAllDB($search){
        global $mysqli;
    
        $out = "";
    
        $sql = "show tables";
        $rs = $mysqli->query($sql);
        if($rs->num_rows > 0){
            while($r = $rs->fetch_array()){
                $table = $r[0];
                $out .= $table.";";
                $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()){
                        $column = $r2[0];
                        $sql_search_fields[] = $column." like('%".$search."%')";
                    }
                    $rs2->close();
                }
                $sql_search .= implode(" OR ", $sql_search_fields);
                $rs3 = $mysqli->query($sql_search);
                $out .= $rs3->num_rows."\n";
                if($rs3->num_rows > 0){
                    $rs3->close();
                }
            }
            $rs->close();
        }
    
        return $out;
    }
    

提交回复
热议问题