Ken-Soft

Software and the World

Create a Multilingual Website in PHP using a MySQL database

Posted under Language Software, PHP, Programming, Software Development, Web Development by Kenny on Tuesday 12 January 2010 at 3:32 pm
Bookmark and Share

In a previous post I showed how to make a simple multilingual website using a hash array. This post will demonstrate how to design a multilingual website in PHP backed by a MySQL database. To see a simple demo open the following link HERE

1. Create the DataBase
First create a MySQL Database called language (or whatever you want). Next, copy the below code into a file (language.sql) and import into your database (import as utf8). You can of course also enter the commands manually. Each language is in it’s own database and has a charset of utf8 to support multiple languages. Every ‘text’ entry is referenced by a corresponding ‘textid’. The textid, for example ‘FNAME’ will appear in each database, but will correspond to a different word depending on the langauge.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CREATE TABLE IF NOT EXISTS `lang_en` (
  `textid` varchar(255) collate latin1_general_ci NOT NULL,
  `text` longtext charset utf8 collate utf8_unicode_ci NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 
CREATE TABLE IF NOT EXISTS `lang_jp` (
  `textid` varchar(255) collate latin1_general_ci NOT NULL,
  `text` longtext charset utf8 collate utf8_unicode_ci NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 
CREATE TABLE IF NOT EXISTS `lang_zh` (
  `textid` varchar(255) collate latin1_general_ci NOT NULL,
  `text` longtext charset utf8 collate utf8_unicode_ci NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 
INSERT INTO `lang_en` (`textid`,`text`) VALUES ('FNAME','First Name'),('LNAME','Last Name'),('SUBMIT','Submit'),('LANG_EN','English'),('LANG_JP','Japanese'),('LANG_ZH','Chinese');
INSERT INTO `lang_jp` (`textid`,`text`) VALUES ('FNAME','名'),('LNAME','姓'),('SUBMIT','確認'),('LANG_EN','英語'),('LANG_JP','日本語'),('LANG_ZH','中国語');
INSERT INTO `lang_zh` (`textid`,`text`) VALUES ('FNAME','名'),('LNAME','姓'),('SUBMIT','确定'),('LANG_EN','英语'),('LANG_JP','日语'),('LANG_ZH','中文简体');

2. Create Language Class in PHP
The below class is just one implementation, so feel free to customize this however you want to fit your needs. Note the usage of the default language. I implement this just in case a user stumbles across a page where the text is not translated so that it can resort to a default. Some text looks better than none :) Having everything in one function getText() or echoText() makes it easy for me to affect all the text on the whole website at once. It also allows me to later add in a “Suggest better translation ” button, or any other number of features that you wish.

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
30
31
32
33
34
35
36
37
38
39
40
<?php
 
// AUTHOR: KENNY CASON
// WEBSITE: WWW.KEN-SOFT.COM
 
class Language {
 
	public $defaultlang = "en";	// Default Language
 
	function Language($defaultlang="") {
		if($defaultlang != "") {
			$this->defaultlang = $defaultlang;
		}
	}
 
    	// get text from DB
	public function getText($textid, $lang="") {
		if($lang == "") {
			$lang = $this->defaultlang;
		}	
      		$query = "SELECT text FROM lang_$lang WHERE textid='$textid'";
      		$result = mysql_query($query);	
        	$row = mysql_fetch_array($result);
		$text = $row[0];
		if($lang == $this->defaultlang) {  // if language is default, return the langauge unchecked.
			return $text;
		} else {
			if($text != "") { // Is text field un-translated? (i.e. not empty string)
				return $text;
			} else { // If not, query using default language
				return $this->getText($textid, $this->defaultlang);
			}
		}	
    	}
 
    	// get and echo text from DB
	public function echoText($textid, $lang="") {
		echo $this->getText($textid, $lang);
    	}
}

3. Put everything together
Finally we will create our index.php file to demonstrate how to use everything. In the beginning of the code connect to the Database of your choice. For the purpose of this simple demo the language parameter ($lang) can be passed to the page, and is English (en) by default. This could ideally be queried from the users profile, etc. Also notice that each time you want to print text just call the appropriate function in the Language class. The below example demonstrates to ways to print the Japanese text (名) referred to by the textid FNAME

1
2
3
4
5
$lang = "jp" // Japanese
// create a new Langauge Object
$obj_lang = new Language();
$obj_lang->echoText('FNAME', $lang);
echo $obj_lang->getText('FNAME', $lang);

Two other VERY IMPORTANT lines are:

1
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

Set the page incoding to UTF-8.

1
mysql_set_charset('utf8', $con);

AND, set the charset for your mysql queries. Otherwise you’ll get a bunch of “?”’s and likely wonder what it is your doing wrong… or at least I did. :P
Here is the whole index.php

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
30
31
32
33
34
35
36
37
38
39
40
41
<?php
include_once("language.php");
 
// connect to a MySql DB, usually have a seperate file, or DB class to do this.
$host = 'dbhost';
$user = 'dbuser';
$password = 'dbpass';
$database = 'dbname'; // I call mine language
 
$con = mysql_pconnect($host, $user, $password);
mysql_select_db($database,$con);
mysql_set_charset('utf8', $con);
 
 
// create a new Langauge Object
$obj_lang = new Language();
 
// ideally pull this from a users profile.
$lang = $_REQUEST["lang"]; 
 
?>
 
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
 
<body>
	<a href="index.php?lang=en"><? $obj_lang->echoText('LANG_EN', $lang); ?></a>|<a href="index.php?lang=jp"><? $obj_lang->echoText('LANG_JP', $lang); ?></a>|<a href="index.php?lang=zh"><? $obj_lang->echoText('LANG_ZH', $lang); ?></a>
	<form>
		<? $obj_lang->echoText('FNAME', $lang); ?>:<input type="text" name="firstname" /><br />
		<? $obj_lang->echoText('LNAME', $lang); ?>:<input type="text" name="lastname" /><br />
		<select name="lang">
			<option value="en"><? $obj_lang->echoText('LANG_EN', $lang); ?></option>
			<option value="jp"><? $obj_lang->echoText('LANG_JP', $lang); ?></option>
			<option value="zh"><? $obj_lang->echoText('LANG_ZH', $lang); ?></option>
		</select><br />
		<input type="submit" value=<? $obj_lang->echoText('SUBMIT', $lang); ?> />
	</form> 
</body>
</html>

Again, the link to the demo using the following code can be found HERE
Hope this is useful to someone.


John Conway’s Game of Life + Mutation (C/C++)

Posted under C/C++, General Development, Mathematics, Programming, Simulation, Software Development by Kenny on Tuesday 22 December 2009 at 7:37 am
Bookmark and Share

I’ve always been interested in AI, evolution simulations, and other interesting problems. But I will never forget one of my all time favorite classics, John Conway’s Game of Life..
This simulation implements a few just a few simple rules, yet relatively complex structures emerge.
The rules are:
1. Any live cell with fewer than two live neighbors dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbors dies, as if by overcrowding.
3. Any live cell with two or three live neighbors lives on to the next generation.
4. Any dead cell with exactly three live neighbors becomes a live cell.

Below are some of the patterns that I found and thought were interesting:

Game of Life Simple Patterns Game of Life Complex Patterns

After watching many trails I noticed one thing immediately; The simulation always eventually “dies down”, or reaches some equilibrium state and it is usually comprised of a bunch of simple structures. So I decided to add a mutation factor to the simulation such that upon mutation, A living cell dies and a dead cell comes to life. This significantly increased the life of the simulation. In fact with the right mutation rate the simulation will continue endlessly.

In my quick little simulation I also introduced a “wrap around” feature so that structures can move infinitely in any direction.

The demo is written in C and uses the SDL Library for drawing the points and is in 640×480 resolution. The source can be downloaded here.
To Compile:
g++ main.cpp -o LIFE -lSDL
To Run:
./LIFE

Every thing from mutation rate to cell generation at startup is configurable. Read the ReadMe.txt file included to see what’s configurable.

Screenshots:

Life Screenshot Life Screenshot Life Screenshot Changed Rule

Notice that the 3rd Image is a result of changing rule 4 to ” Any dead cell with two or three live neighbors becomes a live cell.” (I made this typo when first writing the program and was surprised by the result :)) Try changing the rules and see what results you find.
I hope to release a more complex version in the future.


Neural Network (Back-Error Propagation) C++

Posted under Artificial Intelligence, C/C++, General Development, Neural Networks, Programming, Software Development by Kenny on Sunday 20 December 2009 at 4:42 am
Bookmark and Share

Here is yet another simple Neural Network that implements Back-Error Propagation as a form of Reinforced Learning.
The entire project is written in C++ and requires no special libraries to compile and run.
main.cpp contains code to train both a 2 and 3-input Logical AND gate.
The zipped source code can be downloaded here
A Linux executable is already compiled and included in the zip, but feel free to recompile it. A Code::Blocks Project file is also included.

To Compile
g++ *.cpp -o NeuralNetwork
It will output an executable name “NeuralNetwork”
To Run
open a terminal and type:
./NeuralNetwork
Sample Output
Neural Network Connections Inited
Trained in 10000 trails within an error of 1.03127e-05
0 & 0 = 4.63117e-05
0 & 1 = 0.00349833
1 & 0 = 0.00290835
1 & 1 = 0.995469
Train Logical AND 2 Inputs Demo End
Neural Network Connections Inited
Training...
Trained in 5584 trails within an error of 9.99977e-06
0 & 0 & 0 = 3.62242e-05
0 & 0 & 1 = 0.00194301
0 & 1 & 0 = 0.000102096
0 & 1 & 1 = 0.00344352
1 & 0 & 0 = 0.000142368
1 & 0 & 1 = 0.00333881
1 & 1 & 0 = 0.0035418
1 & 1 & 1 = 0.993633
Logical AND 3 Inputs Demo End

Resources:
About Neural Networks (English)
About Neural Networks (Japanese/日本語)
Java Implementation of a Neural Network


Graph 3D (Vector Rotation Source Included) C++

Posted under C/C++, General Development, Mathematics, Programming, Software Development by Kenny on Saturday 19 December 2009 at 4:17 am
Bookmark and Share

This program implements my simple Vector3D.h source to draw simple graphs using SDL. While it’s not terribly advanced, it should be pretty fun to tinker with. To learn more about 3D rotations including the mathematics and more source (Java) examples, view my previous post –> 3D Rotation Matrix - Graph3D.
The source code and linux executables can be downloaded here.
If you don’t want the Graph utility the single Vector3D.h file can be downloaded here.

Below is a few of the graphs that I created. All of which can be found in main.cpp (there is a section in the code where you can uncomment the function that you want to graph!)

3D  graph 3D  graph 3D  graph 3D  graph
3D  graph 3D  graph 3D  graph 3D  graph
3D  graph 3D  graph 3D  graph 3D  graph
3D  graph 3D  graph 3D  graph 3D  graph
3D  graph 3D  graph 3D  graph 3D  graph

SDL - Simple Space Shooter Game Demo

Posted under C/C++, Game Development, Programming, Software Development by Kenny on Sunday 20 September 2009 at 8:32 pm
Bookmark and Share

This page contains source code for a simple space shooter game written in C++ using the SDL library. There are no enemies or levels, but only a ship that shoots bullets. This is meant for a beginner who is interested in getting started with SDL for use of making games. (This will be an ongoing tutorial)

All source code can be found in the ZIP file
Version Downloads with project files (All you really need is the source):
Version 3: Enemies, Event Queue(timer based), explosions, bullet & enemy collision, some minor code fixes
Version 2: Animated sprites, uses custom sprite class
New to SDL? Start with Version 1 below
Version 1: Project file for DevCpp (Windows)
Version 1: Project file for Code::Blocks (Linux)

Also, for a Sprite class with rotations, animations, etc. Check out my ongoing Sprite library, also written in C++ using SDL
SDL Sprite Library


3D Cube Engine - Java

Posted under Game Development, Java, Programming, Software Development by Kenny on Saturday 27 June 2009 at 10:35 am
Bookmark and Share

This is a recent project of mine for building 3D puzzle games, (like Rubik’s Cubes).

While the code could be optimized quite a bit, this is mainly for those who wish to better understand concepts of 3D programming. For example, one way to create, store, and manipulate a 3D polygon, whether it be a Cube, or an ellipsoid. This project contains code and algorithm’s to rotate 3D polygons, around the origin, and themselves. Ability to draw 3D objects in order of increasing Z-values. Draw wireframe or solid color polygons. Keyboard and Mouse controls to move and alter the Polygons. It is a work in progress and not intended for use in graphic intensive games.

Note: later I will add rotateAroundVector() for more general rotation
Note: Ellipse3D is still very primitive but demonstrates one method creating an ellipsoid
Note: Not all Jar files contain the same versions of code. Each Jar file contains code specific to what it is supposed to do.

All source code can be found in the JAR files
Downloadable Jars (simple to complex):
1. RenderWiredCubes3D-demo.jar: this code rotates 4 rotating cubes about the origin.
2. RenderPolygons3D-demo.jar: this code demonstrates various ellipsoids and cubes rotating around unique axises.
3. Cubes3D-demo.jar: this code demonstrates more of the functionality of the 3D Cube engine by creating a Rubik’s cube like look and feel.
Controls

  • Mouse: click and drag the cube
  • A - reset
  • S - toggle between solid and non-solid mode. (i.e. the inside is filled with cubes or not)
  • D - randomly select an internally defined color scheme
  • F - toggle between random rotate mode. Just try it :)
  • Q - Decrease space between pieces
  • W - Increase space between pieces
  • E - Decrease size of cubes
  • R - Increase size of cubes
  • T - Decrease dimensions. i.e. 4×4x4 -> 3×3x3
  • Y - Increase dimensions. i.e. 4×4x4 -> 5×5x5 (not that if solid mode is true, then it will render slower
  • Arrows - Translate the cubes across the screen

If you’re only interested in the Transformation algorithms, check the below link:
Graph4D - demonstrates methods and actual source code for rotating a 4D vector.
Graph3D - demonstrates methods and actual source code for rotating a 3D vector.


太陽系

Posted under Learning, Science by Kenny on Monday 2 March 2009 at 7:31 pm
Bookmark and Share

これは僕が関西外国語大学にいる時、書いた論文で、内容はそんなに難しくなく、日本語を勉強している人にとって役に立つかもしれません。


Next Page »

Copyright © 2009 www.Ken-Soft.com