Friday, May 30, 2008

CakePHP: Working with View

In the last article, I wrote a 'Hello World' program.
class TestersController extends Controller{
  var $uses=null;
  var $autoRender=false;
  function sayHello(){
    echo 'Hello, CakePHP!';
  }
}
?>

But it has a problem. According to MVC pattern, a controller shouldn't be used for displaying. However, that example uses 'echo' statement in the controller. It is a bad style. In MVC, view is used for showing data. So today I will write something about how to use view to display a page.

A view is usually a file containing much HTML but bit of PHP code. In CakePHP, a controller is associated with some views, depending on its name. For instance, the controller "Testers", its class name is "TestersController" and it must be located in app/controllers/testers_constroller. Its view must be located in app/views/testers/. Each action can have its view. For example, the view of TesterConstroller::sayHello() is app/views/testers/say_hello.thtml. No more to say, let's have a look at the view's content (say_hello.thtml):
Hello, !

You see, it's very simple, just displays a variable $name. Now the questing is: how to pass the variable from the controller? The answer is "set()". Modify the controller class above:
class TestersController extends Controller{
  var $uses=null;
  function sayHello(){
    $this->set('name','Woody');
  }
}
?>
Here, $this->set('name','Woody') set the variable $name. You see, now the controller don't contain output statement. It just set some variables and pass them to a view (because I removed "$autoRender=false", CakePHP will execute app/views/testers/say_hello.thtml). Now open http://localhost/cake/testers/sayHello (suppose your CakePHP project is in WEBROOT/cake/ directory), you will see "Hello, Woody!".

But there's is another problem. The result contains some more we don't want, like the big title "CakePHP Rapid Development" and the CakePHP's logo on the bottom right. Why is it? The answer is "layout". A layout is similar to a view. Considering a real website. It may contain many pages. But all the pages have some same elements, such as top banner, header text, CSS, etc. We don't need to put these things into all views. Just need layout once. Layout is used for sharing common view elements and it is usually a completed HTML file. Since we haven't create our layout, CakePHP will use its own.

Now let's create a default layout. Its file path is "/app/views/layouts/default.thtml". The content:
<html>
<head>
<title><?php echo $title_for_layout; ?></title>
</head>
<body>
<h1>Learn CakePHP</h1>
<?php echo $content_for_layout; ?>
</body>
</html>
And then change the sayHello action into:
function sayHello(){
  $this->pageTitle='This is the title for the layout.';
  $this->set('name','Woody');
}
Then run the action and check the brower's title bar.

How does a controller get data from a view?

Usually, views contain some forms to get users' input. According to MVC, the input data will be passed to controllers. Since it needs more examples, I plan to write something about it in some day in the future.

Wednesday, May 28, 2008

Integrating Adsense into Blogger (for Experts)

Blogger is a famous free blog service provider (BSP). It belongs to Google.com. Although it is free to use, you can use Adsense on you blog to make money. Inserting adsense is very easy. But sometimes we need more. For example, I want to show a 468 x 60 banner above the first article in the index page or achive pages. But I don't want it to be shown in a single post page. Moreover, I want to show another 468 x 60 banner below the article in each single post page only, but it won't appear in the index page or achive pages, etc. See below:
So the simple way won't work. How to solve it?

First we need some software tools. What I will use are Firefox, Firebug extension for Firefox, a text editor (Notepad++). That's all. Now let's begin.

Go to your Blogger -> Layout -> Edit HTML. Download the full template and use your editor to open it. Then use Firefox to visit your blog. Enable Firebug (right click its icon and make sure "Disable Firebug" isn't selected). Then click the icon and you can see the its interface. Click "Inspect" button (top left), and move your mouse on the webpage to find the right HTML code segment. Here's the screenshot.

I used Firebug to find out that the main content is located in a "div" whose id is "content". Then open your editor to find <div id='content'>. Add these lines after it:
<b:if cond='data:blog.pageType != &quot;item&quot;'>
  <div id='index_banner'>
    <b:section id='index-banner-only' locked='false' preferred='yes'>
    </b:section>
  </div>
</b:if>

Save and upload it. Then go to Layout -> Page Elements. You will see a new "Add a Page Element" above the blog posts area. You can add an Adsense banner. This banner won't appear in any single post page.

Now let's add the article page ads. In the same way, use Firebug to find the right HTML code. And then search it in your text editor. Or you can search for "<data:post.body/>". data:post.body stands for the content text. Add these lines below it:
<b:if cond='data:blog.pageType == &quot;item&quot;'>
your adsense code
</b:if >
Because I want to add Adsense below the article, just add Adsense code below it. But it won't work. You must use Ad Code Converter to convert your Adsense code, and then put it into your template.

OK. Now save your template and upload it. Go to "Page Elements" panel to add an Adsense banner. This banner will only display in the index page and archive pages, etc. It won't display in a single post page. However, if you open a single page, the ads below the content will appear.

PS: I think this trick will increase the Adsense CTR.

Monday, May 26, 2008

Foxit Reader: A Better PDF Viewer

I have used Adobe Reader as my PDF viewer many years. But Adobe Reader became fatter and fatter recently. Today when I opened three PDF files with it, my computer became very busy and slow. I open the task manager of Windows. To my surprice, the Adobe Reader used over 100 MB memory space! So I wanted to look for another PDF viewer.

I found Foxit Reader just now. Many people think it's better than Adobe Reader because it's smaller and faster. I have tried it. Very fast even I open five PDF files. That's it.
Foxit_Reader

The disadvantage of Foxit Reader is the font is not as clear as Adobe Reader. I don't know why it is.

XAMPP is The Best Choice for Programmers

XAMPP is an open source suit of Apache, MySQL, PHP/Perl. To many people, installing Apache, MySQL and PHP is difficult. XAMPP integrates them into one package. Moreover, it can run on many operating systems, such as Linux, Windows, Mac OS X and Solaris. With XAMPP, you don't need to edit any configuration file, just unpacking it, even no need to install, you can run your Apache web server with PHP and MySQL support.

Why did I say the XAMPP is appropriate for Programmers? Here are some reasons. First, XAMPP can run on many platforms, you needn't change your program or configuration files if you want to change the operating system. Second, the default configuration of XAMPP is convenient for debug program. So it is not appropriate for the final products. Third, XAMPP provides some add-ons to extend its function. Now you can integrate Perl and Tomcat into XAMPP. Besides, XAMPP contains much PHP extensions, for example, libjpeg, libpng, gdbm, zlib, expat, Sablotron, libxml, etc.

The current version of XAMPP is 1.6.6a. The Windows distribution contains:
  • Apache HTTPD 2.2.8 + Openssl 0.9.8g
  • MySQL 5.0.51a
  • PHP 5.2.5
  • PHP 4.4.8
  • phpMyAdmin 2.11.4
  • FileZilla FTP Server 0.9.25
  • Mercury Mail Transport System 4.52
Do you want a try? Click here.

Update: I received the comments. I agree with them, too. I think a good PHP programmer should know how to configure Apache, PHP and MySQL, etc. I think XAMPP is the best because it makes the work very easy. So it can save much time. Certainly, unstanding how they work is necessary for a good programmer.

Sunday, May 25, 2008

Get Traffic to My Blog

Traffic is the life of a website or a blog. I have been thinking of how to get more traffic to my blog these days. I don't like many people's advice, such as submitting my blog to many directory sites or sending lots of links to forums and so on. I'm not good at it. Since I like programming and I am good at web programming or software. Why could I use my advantages to reach the goal? Just now I found an e-book called 77 Ways to Get Traffic. I think some ideas are so good.
  • Join Wikipedia. Wikipedia is a very successful website and it has much traffic. Especially, anyone can edit it. Althought Wikipedia don't allow anyone to submit spam likes. Fortunately my blog and articles are related to some wikipedia items, I can add the links into the "external links" section. But be careful, don't add spam links.
  • Develop some software. I can make some shareware and freeware and I can add my site link to the software. I believe, by this way, more and more people will know me.
  • Make some playful plugins or gadgets. This method is similar to the above one. But plugins or gadgets are much easier to develop. For example, I can make some WordPress plugins and Google gadgets. I think this is a wonderful thing because I like programming and the more people use my software, the more I am excited.
  • Contribute to some professional websites. Many technology websites accept users' contribution, for example, CodeGuru and CodeProject. I think it is acceptable that put my website's link in the end of my article.
  • Submit some posts to the shareing website, such as Digg or Del.icio.us. I have used it for nearly a month. But unfortunately, the effect doesn't seem good. I think it is more suitable for the websites who have much traffic already.
Certainly, the most is the contents. If you want to build a meaningful website, original and useful contents are most important. Don't think about "garbage sites", whose all contents are copied from other sites. I hate them and I think Google hates them, too.

Saturday, May 24, 2008

Integrating ShareThis into Blogger

Look at the end of each post. I integrated "ShareThis" button into my blog this morning. "ShareThis" is a bookmark widget for bloggers. It can make your visitors share your contents more easily. Now let me tell you how to integrate it into your blog hosted by Blogger.com.

Click here to get the code. It advises you to create an account. But it is not necessary. If you want to obtain the code only, just click "No Thanks" button. Then you can custom the button's appearance. I think the default is not bad for me. So I skipped this step and click the "Get ShareThis Code" button. You'd better copy the code to your favourite editor so that you can use it after a while.

Go to your Blogger administration panel and open "Layout" tab. Then click "Edit HTML" and check "Expand Widget Templates". See below:
sharethis_blogger_1

Add the code in <head>...</head>. It's better to use HTML comment to mark the code.
sharethis_blogger_2

Search for "<data:post.body>" in the template. Add the code below following it:
<p>
<script language='javascript' type='text/javascript'>
SHARETHIS.addEntry({
title: '<data:post.title/>',
url: '<data:post.url/>'
}, {button:true} );
</script>
</p>
sharethis_blogger_3

That's OK. The function "SHARETHIS.addEntry" will create an instance, i.e. the ShareThis button. "title" and "url" are two useful arguments. They specify the post URL and the title. If they are omitted, the current URL and the HTML title are used instead. <data:post.title/> and <data:post.url/> are the Blogger template tags. They stand for the post's title and its permanent URL. If you want to know more about "ShareThis" API, please see the manual.

Thursday, May 22, 2008

PowerShadow: Protect Your Computer

PowerShadow is similar to recovery card. When PowerShadow is running, it seems that you are working on a 'shadow' of the operation system. All changes of files on the hard disk will disappear after rebooting the computer. So you don't afraid of virus any more. Here is a screenshot:


The current edition of PowerShadow costs $39.00. If you don't mind the older edition, you can use PowerShadow 2.6, it is free to use. Mine is PowerShadow 2.6. It can be downloaded from my box.net. Click here.

The free registration information is:
Username: PowerShadow
Serial Number: VVR29E-R4WCK2-K4T111-V1YHTP-4JYJDD

PS: PowerShadow is not anti-virus software. It can only protect your files from being changed or deleted. It can't guarantee that your private information not to be leaked out.

Inserting Math Formula

Although there has been a markup language for mathematics called MathML, it is not convenient because it needs some browser plugins to display math formula, for example, MathPlayer. Up to now, the best way to insert math formula into web pages is converting them into images.

But how to describe a math formula with pure text? The answer is TeX. TeX is a publishing tool for scientist and it is developed by Donald E. Knuth. To use it, you must learn some things about TeX. For example, the square root of 2 can be written as '\sqrt{2}'.

MimeTeX and MathTeX are famous for converting TeX texts into images. If you have your own server, you'd better setup it on the server, although it is a hard work. But what is you haven't your own server? Fortunately, there is a public server, forkosh, providing MimeTeX and MathTeX for free. e.g. if you want to write the squre root of 2, you need to write this HTML:<img src="http://www.forkosh.dreamhost.com/mimetex.cgi?\sqrt{2}" /> or <img src="http://www.forkosh.dreamhost.com/mathtex.cgi?\sqrt{2}" />. i.e. you need to pass TeX text as the mimetex.cgi or the mathtex.cgi's argument. If you know TeX, inserting formula is very easy.

Now let's have look. The TeX text is 'x_{1,2}=\frac{-b\pm\sqrt{b^2-4ac}}{2a}'.

MimeTeX.cgi:


MathTeX.cgi:

Friday, May 16, 2008

5.12 Earthquake

7.8 earthquake happened in Wenchuan, Sichuan Province, China on May 12th. By now, about TWENTY THOUSAND people lost life...Many of the victims are children, many destroyed buildings are schools... DEPRESSED, CRYING...

The more worse is, all information is unreliable (the reason is very complex, please see Wikipedia for more about Chinese media). We don't know how many victims, how are their lives. Most people in China has donated money, but we don't know and can't know where the money has gone.

God, bless them...

Thursday, May 15, 2008

CakePHP: Hello World!

CakePHP is an MVC framework. Model, view, controller are the main components. Generally speaking, the model is an object and is used to operate database. You should employ it to communicate with database, like inserting, deleting, querying. The view is as its name. It is used to display the result. Usually it contains lots of HTML but few PHP code. The controller is employed to handle HTTP requests and do some logic. The controller is central in an MVC pattern. It calls the model to get data from database, then do some work, and sends the result to a view to display.

Let's have a look at CakePHP. I will use CakePHP to write a "hello world" program. My CakePHP is located in D:\xampplite\htdocs\cake. In it there are four directories: app, cake, docs, vendors. "app" is the working directory where we should save our code. Now let's write some codes.

<?php
class TestersController extends Controller{
var $uses=null;
var $autoRender=false;
function sayHello(){
echo 'Hello, CakePHP!';
}
}
?>


As you see, the name of the controller class is TestersController. i.e. The controller's name is Testers. According to the CakePHP convention, the controller's name should be plural form. You must save it as "testers_controller" in app\controllers so that CakePHP can find the controller class.

Before you run it, please make sure that mod_rewrite is on. Check your Apache http.conf, find the line like "LoadModule rewrite_module modules/mod_rewrite.so". If it is commented, just uncomment it (remove "#"). Now start or restart (if you modified http.conf) Apache server. Enter http://localhost/cake/testers/sayHello in your browser's address bar. You can see the result if no problem happens:
cakephp_helloworld


Now let me explain the program in detail. In the TestersController class I define two variables: $uses and $autoRender. $uses specifies which models the controller can use. I set it "null" so that it don't use any model. If I omit it, CakePHP will look for the model "Tester" automatically. That will produce an error because I haven't created the model class. See below:
cakephp_missing_model

$autoRender=false makes CakePHP not search for the view for TestersController::sayHello() because I haven't create the view. If it is omitted, a missing view error will occurred.

The function sayHello() is called "action" in the controller class. That's to say, A controller may have several actions to handle different tasks, and each action is just a function in the controller class. Controllers and actions are mapped into URL. For example, when we open http://localhost/cake/testers/sayHello, CakePHP will find TestersController class and execute sayHello() function automatically. We can call any action by typing different URLs.

That's all. In this example I just used controller to write a "hello world" program. It is just beginning. There are many features in CakePHP. I hope my articles will be helpful for you.

Update: To simplify the example, I use "echo" statement in the controller. That's a bad style. In fact, we should use "view" to show data or result. If you are interested, see Working with View.

Wednesday, May 14, 2008

Start to Learn CakePHP

Choosing a proper PHP framework is difficult (see this). Fortunately, at last, I make a decision that I'm going to learn CakePHP at first. CakePHP is small and easy to use. And there are many free tutorials on the Internet. So I think it is not hard to get help. Also, I used FleaPHP which is developed by a Chinese programmer half a year ago. I feel CakePHP is similar to FleaPHP, and obviously CakePHP is much better and more powerful. It seems to be easier to learn than Symphony or Zend Framework for me.

I downloaded it just now and installed it on my computer according to its manual. It's very simple, just unpack the zip file into a sub-directory located in www root, for example, "cake". Then run your Apache, enter "http://localhost/cake/" in your browser's address bar. You will see a welcome page. If you don't see it, please refer to the manual book. I used XAMPP on Windows, a suit of Apache, PHP and MySQL. CakePHP runs well on it.

Now it is 22:50. I'm going to sleep. I will learn CakePHP formally next day and write some notes here.

Tuesday, May 13, 2008

New Template

According to some suggestions, I changed the template of this blog today. Some people told me that I should use a distinct template instead of Blogger default ones. Also, they told me that it's better to buy a domain. I don't plan to do it. Although a domain costs only about $10/year. I don't think it is necessary.

This template is called Langit and found in eblog templates. There are many beautiful templates. At first I wanted to use Blogging Pro but it has some problems on post page. I don't know how to solve it. So I decided to use Langit. According to the document I added my Adsense code. I feel it is very appropriate for Adsense. The 336 x 280 ad unit on the right side looks good and I hope it will give me more clicks!

After that I configured FeedBurner of the template. So now the feed is hosted by FeedBurner. You can subscribe it through any RSS reader or Email. Just click the RSS logo on the right. I don't want to add "DiggThis" button since I found Digg cannot give me more traffic. The best and easiest way to get more traffic is to make Google to love it. But up to now, Google has indexed about 20 pages of this blog. There is no visitor from Google... But I think it will be better and better if I won't give up.

Thank the guys from Digital Point who gave me advice, encouragement and feedback.

Looking for a PHP Framework

MVC is an import design pattern for web development. I think the easiest way to apply MVC with PHP is to use an appropriate framework. So I have been looking for an appropriate PHP framework for quick development these days. The diffficult thing is that there are too many choices. It seems that the most widely used are Zend Framework, Symphony and CakePHP. I think CakePHP is better because it is lightweight. Symphony has lots of documents, especially it supports AJAX well, but it is said it's hard to learn. Zend Framework is too fat so I doubt if it is convenient to learn and to use.

Also, I found PRADO PHP Framework. It is component-based and event-driven. Event-driven seems interesting. The code style is similar to JSP and ASP.NET.

Which framework do think is best? Maybe I shouldn't waste much time to choose a framework. But unlike JSP, Struts, Hibernate and Spring is enough for almost any web application, frameworks in the world of PHP are too many. That's hard to choose one to start to learn.

Any suggestions?

Monday, May 12, 2008

Blogging Tool: Windows Live Writer

Windows Live Writer is a blog writing tool. It provides a powerful editing environment, like a simple MS Word. You can use it to write on your own computer and after finishing a post just click the publish button. The post will be published.

Since I'm living in China and China blocks all the blogs on blogspot.com sometimes (may be always), so Windows Live Writer cannot connect to the Internet. That's boring.

Here is a screenshot:

Windows Live Writer

PS: Windows Live Writer can only run in Windows XP or above and need .net framework 2.0 support.

How to Change WordPress Login Name?

Here, 'WordPress' refers to the one you own host, not the one BSP provides.

After setting up WordPress, it produces an administrator 'admin'. You can use it to login. But probably you want to change it into another one. You cannot find any options in WordPress management panel. How to do it? The easiest way is to change it in database directly.

Use phpMyAdmin (or another MySQL management tool) to open 'wp_users' table in WordPress database. You can see an 'admin' record. Change 'user_login' field into a name you want. That's OK. For alternatives, you can execute SQL query directly:
use wordpress; -- 'wordpress' is the name of WordPress database
update wp_users set user_login='name you want' where user_login='admin';

After that, you can use the new name to login your WordPress.

Sunday, May 11, 2008

Introduction to Regular Expression

Regular expression is a powerful tool for handling string. For example, it is often used to validate Email, find all URLs in an HTML file, etc. Many programming languages support regular expresiong, such as Java, Python, PHP. Some languages, like C and C++, don't support it though, you may find some libraries (such as Boost) to handle regular expression instead. In this section, I don't want to introduce how to use regular expression in each programming language. In fact, regular express is in common use. Now let's look at the syntax of regular expression. To see clearly, I use '/.../' to describe a regular expression and '...' to describe a normal string. The symbol '~' means 'match'.

Matching strings is the goal which regular expression is designed for. For example, '/ea/' can match all strings contain the characters 'ea', such as 'please', 'reason', 'easy'. The dot '.' can match any character. When some characters are put in '[]', it means 'or'. See below:
'/[bcm]at/' ~ 'bat', 'cat', 'mat', but not 'bmat'. i.e. characters in [] can be matched only once.
'/[a-z]/' matches all strings that contain lower letter. Here, the minus symbol '-' means 'to'. It describes a range.

Let me take more useful examples:

How to validate an IP address? We know that IP address can be expressed as xxx.xxx.xxx.xxx. Here, 'x' stands for a digit. We can use '/([0-9]{1,3}){4}/' to match IP addresses. However, there are some special characters need to be explained. First, '[0-9]{1,3}' means a digit can be repeated one to three times. i.e. it (the subexpression) can match '1','12','123', etc. Second, the parentheses mean 'a group', because we want the subexpression '[0-9]{1,3}' be applied four times. Up to now you know that brackets specify the repeat times. Moreover, {1,} means repeat one or more times. So you can use '/[1-9][0-9]{0,}/' to match any positive integer.

How to validate an email address? An email address consists of an account name, a symbol '@' and a domain name. It's a little harder work. Let's see the regular expression first: '/^[a-zA-Z0-9\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/'. It contains more special characters. the symbol '^' out of [] means it can one match the head of the string. For example, '/^ea'/ matches 'easy' but not 'reason'. By the way, '^' in the [] has another meaning. I will explain it after a while. The dot '.' in [] doesn't stand for any character. In details, if a dot is the first or the last character in [], it just stands for a dot '.'. The plus symbol '+' means 'repeat one or more times'. It is equivalent to {1,}. There is another symbol '*' similar to '+', means 'repeat zero or more times'. The last symbol in the regular express '$', has the opposite meaning of '^'. It means that it matches the tail of the string only. For example, '/ing$/' mathes 'doing', 'seeing', but not 'surprisingly'.

Just now I said '^' in the [] has another meaning. What it it? It means 'not contain'. For example, '/[^0-9]/' can match any non-digit character.

OK, it is just an introduction to regular expression. Regular expression is very powerful tool and it can be very complex. Even you can use it to parse programming code. Now many text editor provides syntax highlight function. It can be implemented with regular expression. It is necessary skill to a programmer.

Saturday, May 10, 2008

Integrate "DiggThis" with Blogger

As you can see, there is a 'Digg' button on each post. To integrate 'Digg' button with Blogger, you need to modify the template. Goto your blogger's panel, then open 'Layout' -> 'Edit HTML'. Check the 'Expand Widget Templates' checkbox, then you can see the whole template. I suggest you to copy it to your favourite text editor, such as Notepad++. It makes you easier to search and modify the HTML template.

Find this line: <div class='post-body entry-content'>. Add the javascript code below after this line:
<b:if cond='data:post.url'>
  <p style="float: right;margin: 4px;">
    <script type="text/javascript">
      digg_url = '<data:post.url/>';
      digg_window = 'new';
      digg_title = '<data:post.title/>';
      digg_topic = 'programming';
    </script>
    <script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script>
  </p>
</b:if>

Now let me explain. style="float: right;margin: 4px;" is CSS code. It specifies Digg button should appear on the right side and the width of the space between the button and text around is 4 pixels. digg_url = '<data:post.url/>'; sets the URL of each post. If you don't set this variable, Digg button will be attached to the current URL, not the post's URL. digg_window = 'new'; means when the button is pressed, the browsing will open a new window to open digg.com. The next two variables are useful for submitting a post. They specify the default title and the default topic, but users can change them manually.

OK. After you finish it, click 'Save Template' to save the template. You will see a Digg button in every post.

Friday, May 9, 2008

Try Backlinks

I told my friend tonsh to turn on backlinks on her blog. What are backlinks? A quick answer is "backlinks display other webpages that link to your posts". If you turn on backlinks, and if another webpage contains a link to one of your post, you can see a link to that webpage. It is similar to "trackback". Trackback is a method to join different blogs. For example, if you see an interesting article on other's blog and want to post an article about it on your own blog, you can use trackback. Your blog will send a short message to the other's to tell that blog: hey, I'm interested about you, my link's url is ... Then your article's link will appear on his blog.

But blogger.com doesn't support trackback, it uses "backlink" instead. You need only add a link to a post which is on blogger.com in your article. After a while (maybe a few days), a link to your post will appear below his article. Backlink depends on Blogger Search Engine.

Let me try it. Here is a link to one of my friend's posts. When will it appear on the post?

Make Money?

I have been browsing DigitalPoint Forums these days. Many people are making money with their websites or blogs. So I'm considering whether I can make some money with this blog.

I've been using Google Adsense, but the effect is not good. Last year I started Adsense but now my account has only $2.16. What a pity! Of course that blog is written in Chinese. Most people think that English content may bring better ads. Last year I planned to write English but I'm afraid my English level. Now I know, no matter how much I will earn, I will be successful, because I can improve my language level and share my experience all over the world.

I registered LinkWorth for my Chinese blog last day. LinkWorth is similar to Text Link Ads and it supports paid reviews and text link ads, etc. Besides, LinkWorth is more appropriate for small blogs. If your site's traffic is small, you should try LinkWorth probably. But I regret that there are few Chinese ads. It doesn't matter, I think. By the way, LinkWorth provides a tool which can evaluate your site's value. I tried it for my Chinese blog. Surprisingly, it told me a link ads on my homepage values $50 - $60. I don't know how it works. Maybe it's just a joke?

PS: If you want to try LinkWorth, please use this link to register and enter 12368 in referral id. So when you earn $100 I will get $50. Thank you.

Wednesday, May 7, 2008

The Difference Between mysql_fetch_array() And mysql_fetch_assoc()

Getting data from MySQL with PHP is very convenient. But I found most of PHP beginners don't know the difference between two MySQL functions: mysql_fetch_array() and mysql_fetch_assoc(). If you don't understand the two functions, you always come up against such problem: why can't I see the result from MySQL?

Suppose we have a database called 'test' and it has a table called 'members' which stores some members' information. The goal is to fetch all the members' information. Consider such code below:

$conn=mysql_connect('localhost','root','');
$mysql_select_db('test');
$rs=mysql_query('SELECT * FROM members');


Then $rs is an array that stores all personal information. You can use mysql_fetch_array() or mysql_fetch_assoc() to fetch each row by calling the function repeatedly. Consider:

while ($row=mysql_fetch_array($rs,MYSQL_NUM)){
// ...
}

Here $row is a normal array (integer-indexed array). You cannot get data with $row['name'], $row['birthday'], etc. You must use integer as the index, e.g. $row[0], $row[1]... How to get an associative array? You need to set the second parameter of mysql_fetch_array(). MYSQL_ASSOC tells mysql_fetch_array() to return an associative array. See below:

while ($row=mysql_fetch_array($rs,MYSQL_ASSOC)){
// ... here you can use $row['name'], $row['birthday']...
}


mysql_fetch_array($rs,MYSQL_BOTH) equals to mysql_fetch_array($rs). There's no need to use MYSQL_BOTH, so we often omit it.

So you can use two methods to fetch data by specifying the second parameter to MYSQL_BOTH or omitting the second parameter. Then both of the styles, $row[0] and $row['name'], are available.

But where's mysql_fetch_assoc()? It seems not useful. Right. mysql_fetch_assoc($rs) is equivalent to mysql_fetch_array($rs,MYSQL_ASSOC). Obviously, when you need to an associated array (string-indexed array) only, mysql_fetch_assoc() is more convenient. By the way, mysql_fetch_assoc doesn't have the second parameter. It can only return associative array so it needs less memory space to store the result array.

Sunday, May 4, 2008

I Feel Afraid

When you are using Internet to send information, do you think that your information can be viewed on the Internet? Well, it is technically feasible. For example, if you want to send a mail, after you press "send" button, the mail will be sent to an SMTP server, then it will be transferred among several servers. Don't forget that your mail is usually plain text. Everyone can understand your mail if he can access to the mail server where your mail is located.

I feel afraid...

Maybe the best way is that everyone has a pair of RSA password keys. One for yourself (private key) and the other for public (public key). The passwords is two very large number. For example, if you have two numbers m and n, where m is your private key and n is your public key. Before you send a mail, you can use m to encrypt your message. When the recipient received the mail, he can use n to decrypt the message. Remember, n is your public key so your friend can get it, but you must protect your private key. If your friend wants to send mail to you, he need to use your public key, n, to encrypt the message. Then after you recieved the cryptographic message, you need to use your private key, m, to decrypt the message.

Wrote lots of things regarding RSA encryption algorithm. I think it's safety enough for business. But what if your friends who know your public key betray you, e.g. tell your public key to other suspicious people, then he can decrypt your message? I don't know how to avoid it.

There are some tools which support RSA, such as GnuPG (opensource software), PGP Desktop (commercial software).

Friday, May 2, 2008

Running PHP In The Console

When you test a small PHP script, you need run a web server, such as Apache, then open a browser to see the result. How dirty the work is! The simple method to run a PHP file is to call PHP interpretor in the console.

For Unix/Linux, the only thing you need to do is enter such line in the console:

php -f your_php_file


For Windows, the best way to run a PHP script is to call PHP interpretor from a text editor or IDE. I like SciTE, a powerful text editor for programming. Open html.properties from options menu, then add these lines in the bottom:

PHP_Bin=D:\xampplite\php
command.go.$(file.patterns.php)=$(PHP_Bin)\php.exe -f "$(FileNameExt)"
command.compile.$(file.patterns.php)=$(PHP_Bin)\php.exe -l "$(FileNameExt)"


"PHP_Bin" specifies where the PHP interpretor is. After doing that, when you open a PHP file next time, you can run it in SciTE just select "Tools" -> "Go" or press F5. If you select "Tools" -> "Compile" or press Ctrl+F7, PHP interpretor doesn't run the script but check syntax instead.

Thursday, May 1, 2008

What's BBCode?

BBCode is short for "Bulletin Board Code". It is a markup language which is similar to HTML and it is widely used on forums. So it is also called "forums code". Many forums don't accpte HTML code so you can't use HTML to format your text. Most of forums support BBCode. For example, if you want to use bold text, just type "It is [b]bold text[/b]." then the program of the forum changes it into HTML code "It is <b>bold text</b>.".

Below are most useful BBCode markups:
  • [b]bolded text[/b]: bolded text
  • [i]italicized text[/i]: italicized text
  • [u]underlined text[/u]: underlined text
  • [url]http://deepbluespaces.blogspot.com/[/url]: http://deepbluespaces.blogspot.com/
  • [url=http://deepbluespaces.blogspot.com/]Deepblue Spaces[/url]: Deepblue Spaces
The normal method to parse BBCode is "Regular Expression" which is widely used to handle string problem. I plan to write something about regular expression in a few days.