Run a script on every column of every table in your MySQL database
June 23, 2012
Have you ever needed to recursively run a script in a loop on every single column in your MySQL database? This PHP code can help.
// Start by getting the list of tables.
$tables_result = mysql_query("SHOW TABLES FROM `$database`") or exit("Error " . mysql_errno() . ": " . mysql_error());
while ($tables_row = mysql_fetch_row($tables_result)) {
// Loop through the tables. Get the list of columns from each table.
$table = $tables_row[0];
$columns_result = mysql_query("SHOW COLUMNS FROM `$table`") or exit("Error " . mysql_errno() . ": " . mysql_error());
while ($columns_row = mysql_fetch_row($columns_result)) {
// Loop through the columns in the table.
$column = $columns_row[0];
/* --------- Anything you want happens between here... --------- */
echo "$table $column\n";
/* ---------------------- ...and, here =) ---------------------- */
}
}