Monday, May 28, 2012

Php mysql collation change script for tables and fields

<?php

$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'dbname';

$db = mysql_connect($host, $username, $password);
  mysql_select_db($dbname);

$mysqldatabase = 'dbname';
$collation = 'CHARACTER SET utf8 COLLATE utf8_general_ci';

echo '<div>';
mysql_query("ALTER DATABASE $mysqldatabase $collation");

$result = mysql_query("SHOW TABLES");

$count = 0;
while($row = mysql_fetch_assoc($result)) {
$table = $row['Tables_in_'.$mysqldatabase];
mysql_query("ALTER TABLE $table DEFAULT $collation");
$result1 = mysql_query("SHOW COLUMNS FROM $table");
$alter = '';
while($row1 = mysql_fetch_assoc( $result1)) {
if (preg_match('~char|text|enum|set~', $row1["Type"])) {
if(strpos($row1["Field"], 'uuid')){
// why does this not work
}else{
$alter .= (strlen($alter)?", \n":" ") . "MODIFY `$row1[Field]` $row1[Type] $collation" . ($row1["Null"] ? "" : " NOT NULL") . ($row1["Default"] && $row1["Default"] != "NULL" ? " DEFAULT '$row1[Default]'" : "");
}
}
}
if(strlen($alter)){
$sql = "ALTER TABLE $table".$alter.";";
echo "<div>$sql\n\n</div>";
mysql_query($sql);
}
$count++;
}
echo '</div>';

?>

No comments:

Post a Comment

Please Comment Here!

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...