Web Hosting Talk







View Full Version : How to alter all tables in MYSQL with only one command


HelpHelp
03-28-2008, 12:16 PM
Tried and tried could not find the command
I have this

ALTER TABLE table_name_goes_here CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;


but if I use it I have to do with all tables
how can I use the above command in a way to change all tables
in one particular database:mad:

Steve_Arm
03-28-2008, 01:30 PM
PHP it.

$tbls = array('t1','t2','t3','t4');
foreach ($tbls as $t)
{
$query = "ALTER ".$t."CONVERT ..... ";
$res = mysql_query($query);
}
You need the ALTER privilege for that.

etogre
03-28-2008, 02:40 PM
<?php
// your connection
mysql_connect("localhost","root","***");
mysql_select_db("db1");

// convert code
$res = mysql_query("SHOW TABLES");
while ($row = mysql_fetch_array($res))
{
foreach ($row as $key => $table)
{
mysql_query("ALTER TABLE " . $table . " CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci");
echo $key . " =&gt; " . $table . " CONVERTED<br />";
}
}
?>

Tested. Works. Depending on how many tables are in the database it can take a few moments. My database had 76 tables and it took about 20 seconds.

HelpHelp
03-29-2008, 01:04 AM
thanks a lot

what should I put here is this correct?

mysql_connect("localhost","DBusername","DBPassword");
mysql_select_db("mydatabasename");

so I make a php and run it in my browser?

etogre
03-29-2008, 01:15 AM
yep, just edit that part like you did, stick it in a PHP file and then run it.

You will recieve output like this, and you will know it has run fine:

0 => tablename CONVERTED
Tables_in_dbname => tablename CONVERTED
0 => table2 CONVERTED
Tables_in_dbname => table2 CONVERTED
etc..

Tanja
11-19-2009, 08:03 AM
Just wanted to say THANKS!!!! I lost almost 10 hours trying to solve a problem with UTF8 in my MySQL base ... and you definately saved a lot of my nerves!

Thanks again!!!

Be fine!

mattle
11-19-2009, 12:22 PM
FYI...provided you have the PHP CLI binary...you should just be able to do this on the command line:

# php myScript.php