Created
August 1, 2013 22:59
-
-
Save virullius/6136098 to your computer and use it in GitHub Desktop.
Search MySQL schema for a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
$usage = array( | |
'min_args' => '5', | |
'message' => "$argv[0] --host=example.com --schema=MyDB --user=user_name [--pass=\"secret\"] --search=\"any string\"" | |
); | |
if( $argc < $usage['min_args'] ){ | |
exit("{$usage['message']}\n"); | |
} | |
foreach( $argv as $arg ){ | |
$arg_parts = split('=', $arg); | |
if( count($arg_parts) == 2 ){ | |
$arg_name = ltrim($arg_parts[0], '-'); | |
$arg_value = $arg_parts[1]; | |
$$arg_name = $arg_value; | |
} | |
} | |
if( !isset($pass) ){ | |
echo "Enter password:"; | |
`stty -echo`; | |
$pass = trim(fgets(STDIN)); | |
`stty echo`; | |
echo "\n"; | |
} | |
if( !isset($host) || !isset($user) || !isset($pass) || !isset($schema) || !isset($search) ){ | |
exit('Unknown failure'); | |
}else{ | |
$column_query = " | |
select t.table_name, c.column_name | |
from information_schema.columns c | |
join information_schema.tables t on t.table_name = c.table_name | |
join information_schema.schemata s on s.schema_name = t.table_schema | |
where s.schema_name = '$schema' | |
and ( | |
c.data_type like '%text' | |
or c.data_type like '%char' | |
or c.data_type like '%blog' | |
) | |
"; | |
$mysqli = new mysqli($host, $user, $pass); | |
if( $mysqli->connect_errno ){ | |
exit("Failed to connect to MySQL: ({$mysqli->connect_errno}) {$mysqli->connect_error}"); | |
} | |
echo "Connected to MySQL: {$mysqli->host_info}\n"; | |
$column_res = $mysqli->query($column_query); | |
echo "Searching...\n"; | |
if( $column_res->num_rows == 0 ){ | |
echo "No columns found in '$schema' with types *text, *char or *blob\n"; | |
}else{ | |
while( $row = $column_res->fetch_assoc() ){ | |
$data_query = "select {$row['column_name']} from {$schema}.{$row['table_name']} where {$row['column_name']} like '%{$mysqli->escape_string($search)}%'"; | |
if( $data_res = $mysqli->query($data_query) ){ | |
if( $data_res->num_rows > 0 ){ | |
echo "\t'$search' found in [{$row['table_name']}].[{$row['column_name']}]\n"; | |
flush(); | |
} | |
} | |
} | |
} | |
$mysqli->close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just found this feature in MySQL Workbench 6.0!!!
It even supports searching using LIKE.