Search text in fields in every table of a MySQL database

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

    i got this to work. you just need to change the variables

    $query ="SELECT `column_name` FROM `information_schema`.`columns` WHERE `table_schema`='" . $_SESSION['db'] . "' AND `table_name`='" . $table . "' ";
    $stmt = $dbh->prepare($query);
    $stmt->execute(); 
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);       
    
    $query="SELECT name FROM `" . $database . "`.`" . $table . "` WHERE ( ";
    foreach ( $columns as $column ) {
        $query .=" CONVERT( `" . $column['column_name'] . "` USING utf8 ) LIKE '%" . $search . "%' OR ";
    }
    $query = substr($query, 0, -3);
    $query .= ")";
    
    echo $query . "
    "; $stmt=$dbh->prepare($query); $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); echo "
    ";
    print_r ($results );
    echo "
    ";

提交回复
热议问题