search key word in whole Database in mysql and php

Below is the code for key word analysis,


$database = 'databasename';$criteria = '*keyword*'; // you can use * and ? as jokers
$dbh = new PDO("mysql:host=127.0.0.1;dbname={$database};charset=utf8", 'root', '');

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tables = $dbh->query("SHOW TABLES");
while (($table = $tables->fetch(PDO::FETCH_NUM)) !== false){
    if(strpos($table[0], "cache") === false && strpos($table[0], "sessions") === false && strpos($table[0], "watchdog") === false){    
       $fields = $dbh->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?");   
       $fields->execute(array ($database, $table[0]));
       $ors = array ();    
while (($field = $fields->fetch(PDO::FETCH_NUM)) !== false)    {        
       $ors[] = str_replace("`", "``", $field[0]) . " LIKE REPLACE(REPLACE(REPLACE(REPLACE(:search, '%', '\\%'), '_', '\\_'), '*', '%'), '?', '_')";    
}
    $request = 'SELECT * FROM ';    $request .= str_replace("`", "``", $table[0]);    $request .= ' WHERE ';    $request .= implode(' OR ', $ors);    $rows = $dbh->prepare($request);
    $rows->execute(array ('search' => $criteria));
    $count = $rows->rowCount();    
if ($count == 0)    {        continue;    }
    $str = "Table '{$table[0]}' contains {$count} rows matching '{$criteria}'.";    
    echo "
".str_repeat('-', strlen($str)+10)."
"; echo $str; echo "
".str_repeat('-', strlen($str)+10) ."
"; $counter = 1; while (($row = $rows->fetch(PDO::FETCH_ASSOC)) !== false) { $col = 0; $title = "

Row #{$counter}:"; echo $title; foreach ($row as $column => $value){ echo (($col++ > 0) ? str_repeat('-', 3) : ' '), $column, ': ', trim(preg_replace('!\s+!', ' ', str_replace(array ("\r", "\t", "\n"), array ("", "", " "), $value))), "
"; } echo "
"; $counter++; } } }
Above code I have used in drupal site, So some change needed to match your requirement.

Comments

Popular posts from this blog

PHP - How to increase size of POST value in php

D8 KernelEvents constants

D8 - Attach file programmatically to a node