Archive for 'mysql'

Convert the character set of a mysql database

This php-script is for converting content of all tables of a mysql database to another character set. In this case i convert everything (latin 8859-1) to utf8_swedish_ci. The same action can be made from the shell with mysqldump and iconv, but the programmer in me prefers the-php-way. As always, tweaks and comments are very helpful.

<?

set_time_limit(0);

$link = mysql_connect(‘localhost’, ‘mysql_user’, ‘mysql_password’);

mysql_select_db(‘db’);

$sql = "SHOW TABLES FROM db";
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
{
$sql = "ALTER TABLE ".$row[0]." CONVERT TO CHARACTER SET utf8 COLLATE utf8_swedish_ci";
mysql_query($sql);
echo ‘Converting table: ‘.$row[0].’<br>’;
}

?>

MySQL – replace – sök och ersätt

En smidig funktionalitet i MySQL för att göra enkla sökningar-ersättningar (find-replace) i texter är att använda sig av strängfunktionen replace. Den har visat sig väldigt användbar då jag av misstag fått in en massa junktext i databasen och måste rätta detta.

Syntax:
REPLACE(sträng,från_sträng,till_sträng)

Exempel:
mysql> SELECT REPLACE(‘www.mysql.com’, ‘w’, ‘Ww’);
Resultat> ‘WwWwWw.mysql.com’