Artur’s Blog

past, present and future in web development

Jak przekonwertować bazę danych z ogonkami na UTF8

Posted on | February 11, 2010 | No Comments

Podczas tworzenia jednego z moich serwisów (www.rabatek.pl) popełniłem bardzo duży błąd: zaraz po ustanowieniu połączenia do bazy nie zmieniłem kodowania na UTF8 (domyślnie bylo latin1). Wszystko przez to że po raz pierwszy postanowiłem skorzystać z klasy PEAR::MDB2 i mi to umknęło.

W każdym bądź razie strona już sobie istnieje kilka miesięcy i wszystko super działa - do czasu. W wersji beta przerobiłem wyszukiwarkę i okazało się, że jak wpiszę np. “Wrocław” to nic nie znajduje - wszystko przez te piekielne ogonki. Baza ma już w tej chwili kilka tysięcy rekordów więc ręczne poprawianie odpada całkowicie.

Z pomocą przyszedł bardzo prosty skrypt PHP. Napisałem go w 15 minut i nie ma w nim kontroli błędów, komentarzy itp - po prostu wykonuje swoją robotę i tyle.

Postanowiłem się tym skryptem z wami podzielić gdyż wiem że nie tylko ja mam problem z ogonkami.

Uwagi i komentarze mile widziane

 
define('DB_HOST',              'twoje_ip');
define('DB_USER',               'user_do_bazy');
define('DB_PASS',               'haslo_do_bazy');
define('DB_NAME',               'nazwa_bazy');
 
define('DB_CHARSET',            'UTF8');
define('DB_NAMES',               'UTF8');
define('DB_COLLATION',         'utf8_general_ci');
 
function chars_translate($string) {
 
    $org_letters = array('ą','ć','ę','ł','ń','ó','ś','ź','ż','Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ź','Ż');
    $utf8_letters = array('ą','ć','ę','ł','ń','ó','ś','ź','ż','Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ź','Ż');;
    $string = str_replace($org_letters, $utf8_letters, $string);
    return $string;
}
 
$link = @mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$link) {
    echo "error connection to the database: ".mysql_error();
}
 
if (!mysql_select_db(DB_NAME, $link)) {
    echo "error selecting a database: ".mysql_error();
}
 
$tables = array();
 
// odczytaj wszystkie tabele
$query = "SHOW TABLE STATUS ";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
    if ($row['Comment'] != 'VIEW') {
        $tables[] = $row['Name'];
    }
}
 
// pobierz dane ze starych tabeli
$records = array();
foreach ($tables as $table) {
    $query = "SELECT * FROM ".$table;
    $result = mysql_query($query);
    $records[$table] = array();
    $i = 0;
    while($row = mysql_fetch_assoc($result)) {
        foreach ($row as $key => $value) {
            $records[$table][$i][$key] = chars_translate($value);
        }
        $i++;
    }
}
 
// ustaw poprawne kodowanie
mysql_query("SET CHARACTER SET ".DB_CHARSET);
mysql_query("SET NAMES ".DB_NAMES);
mysql_query("SET collation_connection = ".DB_COLLATION);
 
// stworz nowe tabele i wypelnij je danymi
foreach ($tables as $table) {
    $query = "CREATE TABLE ".$table."_new LIKE ".$table;
    $result = mysql_query($query);
 
    if (empty($records[$table])) {
        continue;
    }
    $columns = implode(",", array_keys($records[$table][0]));
    $query = "INSERT INTO ".$table."_new (".$columns.") VALUES ";
 
    foreach ($records[$table] as $row) {
        $query .= "('".implode("','", $row)."'),";
    }
 
    $query = substr($query, 0, -1);
    $result = mysql_query($query);
 
    // skasuj stara tabele
    $query = "DROP TABLE ".$table;
    $result = mysql_query($query);
 
    // zmien nazwe tabeli
    $query = "RENAME TABLE ".$table."_new TO ".$table;
    $result = mysql_query($query);
 
    echo "gotowy ".$table."<br>\n";
    flush();
}
 
echo "KONIEC<br>\n";

How to use SVN on 1and1 account

Posted on | February 10, 2010 | No Comments

When creating a project it is always wise to use some version control program.

I prefer to use SVN it is fast, easy to use and its support is build in in NetBeans IDE. Since I use hosting at 1and1 I tried to install my own SVN repository there. It is very easy and it worked almost instantly.

First step: create svn repository on the server.

Just SSH to your account and create a new directory and svn repository in it:

cd /
mkdir svn
svnadmin create /kunden/homepages/……/htdocs/svn

to get a full path to your home directory call “pwd” command and replace ……. with your information

Now your svn repository is set up - we can procees to the second step: netbeans configuration

from putty download page (here) get plink.exe and place it in c:\Program Files\Putty\ (you can choose different path)
now in your Project window right click on your project name and select Versioning->Import into subversion repository
for Repository URL select svn+ssh:// and enter:svn+ssh://your.domain.com/kunden/homepages/……./htdocs/svn (same path that you have used for svnadmin command)
then as Tunnel Command enter: C:/Program Files/Putty/plink.exe -l ssh_username -pw ssh_password
click Next
now in “Repository Folder” enter desired name like “my_project”
enter a message - for example “initial import”
click Next again
after a while you will be prompted what files you want to import - usually you want to import whole project so just click Finish

And you are done - enjoy your SVN on 1and1 account

the only thing that I don’t like is having open text password for my ssh account in netbeans - it I find a way to hide somewhere I will share it with you

resize an image function

Posted on | July 2, 2009 | No Comments

I wrote this function long time ago and I have used it so many since then. I decided to publish it.

You can find plenty of similar functions but this one is a little bit different. As a parameter you specify new MAX dimensions so image will be scaled based on its height or width. I believe I have enough comments in the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public function resize($source_image, $target_image, $new_width, $new_height) {
  // get current size
  list($width, $height) = @getimagesize($source_image);
 
  if ($width > $new_width || $height > $new_height) {
    $scale1 = $width / $new_width;
    $scale2 = $height / $new_height;
 
    // check if we should scale using width or height
    $scale = $scale1 > $scale2 ? $scale1 : $scale2;
 
    // make sure we scale correctly
    $new_height = floor($height / $scale);
    $new_width = floor($width / $scale);
 
    // Load
    $thumb = imagecreatetruecolor($new_width, $new_height);
    $source = imagecreatefromjpeg($source_image);
 
    // Resize
    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
 
    // Save the file at 95% quality
    imagejpeg($thumb, $target_image, 95);
  } else {
    // image small already - don't resize
    copy($source_image, $target_image);
  }
}

“Cytrynowka” Polish Lemon Vodka

Posted on | May 18, 2009 | No Comments

I was supposed to write about web development but recently I found my old recipe on how to make your own ‘cytrynowka’. All you need is:

  • 1L 190 proof alcohol (I use EVERCLEAR 190 PROOF GRAIN ALCOHOL)
  • 8-10 lemons (depends on size)
  • 1.5 glass of sugar
  • little bit of salt
  • 1L of water

- Ok so to start you have to wash lemons and cut off the ends (and throw them away). Cut all lemons into the pieces (about 1/4 - 1/2 inch in size).

- Put lemon pieces into the metal bowl or pot, add sugar, salt and one glass of water. Squeeze the lemons very well and leave like that for about 2 hours (don’t forget because it will become bitter if you keep it to long)

- soak and remove lemon pieces, filter everything (use gauze pads to filter out even the smallest pieces of lemon). Add 3 glasses of water

- in about 2-3 days filter everything again

- 5 days later it is ready to drink :) best served chilled in shot glasses :)

enjoy

Cracking the Human Resource Code

Posted on | April 29, 2009 | No Comments

“COMPETITIVE SALARY”
Most of our competitors don’t pay much either.

“JOIN OUR FAST-PACED COMPANY”
We have no time to train you.

“CASUAL WORK ATMOSPHERE”
You’ll be here very late, very often — might as well be comfortable.

“MUST BE DEADLINE-ORIENTED”
Your first four projects are already way overdue.

“SOME OVERTIME REQUIRED”
Did we mention that you’ll be here very late, very often? And most weekends.

“DUTIES WILL VARY”
Anyone in the office can boss you around.

“MUST HAVE AN EYE FOR DETAIL”
We have no quality control.

“CAREER-MINDED”
Female applicants must be childless.

“APPLY IN PERSON”
If you’re old, fat or ugly, that position has already been filled.

“NO PHONE CALLS PLEASE”
This job listing is just a legal formality. The position was filled by some executive’s nephew.

“SEEKING CANDIDATES WITH A WIDE VARIETY OF EXPERIENCE”
Due to consolidation, you’ll be replacing three people.

“PROBLEM-SOLVING SKILLS A MUST”
This company is a total mess.

“REQUIRES TEAM LEADERSHIP SKILLS”
You’ll have all the responsibilities of upper management, without the pay, title or respect.

“GOOD COMMUNICATION SKILLS”
Listen to management, figure out what they want, don’t ask too many questions and get the sh*t done.

Why should you use jQuery

Posted on | September 3, 2008 | No Comments

If you ask me one year ago “have you seen jQuery” my answer would be “have you seen what?”

If you ask me six months ago I would say “I heard about it but I don’t see any benefit in using it. I know javascript well enough to write my own code”.

And I was sooooo WRONG.

I just finished small project for my friend www.jardinsdesreves.pl and I decided to give it a try.
The benefit: my js file is only 170 lines long.

I just want to show you couple benefits of this wonderfull framework.

FORMS:

I have never seen a simpler way to submit forms via ajax.

Just look at the simple example:

1
2
3
4
5
6
7
<form>
  <input type="hidden" name="id" value="2">
  <input type="hidden" name="save" value="1">
  Title: <input type="text" name="form_title"><br>
  Content: <textarea name="form_content" cols="25" rows="8"></textarea>
  <input type="button" value="Save changes" onclick="sendForm('text_save.php');">
</form>
1
2
3
4
5
6
7
8
9
10
function sendForm(post_url) {
  var request = $("form").serialize();
  $.post(post_url, request, function(data) {
    formResponse(data);
  });
}
 
function formResponse(resp_data) {
  $("#message").text(resp_data);
}

As you can see jQuery does all job for us.
There is only one requirement - each form element needs to have a name (not id).

serialize() function does great job and will post all form to ‘text_save.php’ where we can do processing and show response to the user.

In the next article I will show you how to use great jQuery plugin ‘ajaxfileupload.js’ to upload files.

no “Hello world” today

Posted on | August 18, 2008 | No Comments

This is just a beginning.

I hope to find enough time to write some articles about web development (PHP, Javascript, CSS, Flex …) and my hobby photography.

I spend a lot of time writing code and even more time googling around for help and solutions. I know how difficult it is to find something useful. That’s why on my blog I will post only useful information and I will try not to copy anything that is already posted on other blogs.

Don’t expect to find a new post every day but if you have any questions or comments to my articles I will respond ASAP

Lets get started :)

About

I will add soon ...

Subscribe to our feed

Search

Admin