Change the MySQL database table encoding to UTF8 with PHP

Posted by Shek on June 10, 2009 under PHP | Be the First to Comment | Total View: 5,640 views

Editor’s note: In some cases, when you have forgotten to preset the MySQL database table encoding to UTF8 after the creation of the database but later you need to insert some UTF8 text such as Chinese or other Asian languages, here is how you could do with PHP to change the encoding of the MySQL database table.


A php file named “alter.php” is created:

First we have to connect to the database:

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Then we create a query which is for changing the MySQL table encoding to UTF8 and the query is stored into a variable $query:

$query ="alter table tablename convert to character set utf8 collate utf8_general_ci";

Then we run the query and to see if it works, a conditional statement if,else is added.

if(mysql_query($query)){
echo "table alter to UTF8";}
else{
echo "fail";}

All together we have for “alter.php” file:

1
2
3
4
5
6
7
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$query ="alter table tablename convert to character set utf8 collate utf8_general_ci";
if(mysql_query($query)){
echo "table alter to UTF8";}
else{
echo "fail";}

Not what you want? Try a Search

Add A Comment

*