vineri, octombrie 03, 2008

O metoda de a migra datele din Mysql Latin1 in Mysql utf8

Scriptul tabelelor latin1 si utf8:
--
-- Structura de tabel pentru tabelul `latin1`
--
CREATE TABLE IF NOT EXISTS `latin1` (
`id` int(10) unsigned NOT NULL auto_increment,
`n` varchar(45) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=5 ;

-- --------------------------------------------------------

--
-- Structura de tabel pentru tabelul `utf8`
--

CREATE TABLE IF NOT EXISTS `utf8` (
`id` int(10) unsigned NOT NULL auto_increment,
`n` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=48 ;


Scriptul PHP de migrare a datelor:

<?php
header('Content-type: text/html; charset="utf-8"');
$link=mysql_connect (server, user, pass);
mysql_select_db (database);

$charset1 = mysql_client_encoding($link);

mysql_query("SET CHARACTER SET utf8", $link);
mysql_query("SET NAMES 'utf8'", $link);

$charset2 = mysql_client_encoding($link);

//test posting

if ($_POST["name"]){
$n=$_POST["name"];
$s="insert into latin1(n) values('".$n."')";
mysql_query("SET NAMES 'latin1'");
mysql_query($s);
$s="insert into utf8(n) values('".$n."')";
mysql_query("SET NAMES 'utf8'");
mysql_query($s);
}
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";

echo "<head>\n";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n";
echo "</head>\n";
echo "<body>\n";
echo "<form method=\"post\" name=\"form\" action=\"utf8.php\">\n";
echo "<input type=text name=name>";
echo "<input type=submit>";
echo "</form>";
echo "<table border=1>";
echo "Setul de caractere pina la SET CHARSET este: $charset1<br>";
echo "Setul de caractere dupa SET CHARSET este: $charset2<br>";

echo "<table border=1>\n";
$s="select * from latin1";
mysql_query("SET NAMES 'latin1'");
$r=mysql_query($s);
while ($row=mysql_fetch_assoc($r)){
echo "<tr><td>".$row["n"]."</td></tr>";
$s="insert into utf8(n) values('".$row["n"]."')";
mysql_query("SET NAMES 'utf8'");
mysql_query($s);
}
echo "</table>";

echo "</body>\n";
echo "</html>\n";
?>

Membri

Comentarii