Friday, December 2, 2011

寄人籬下

最近因為老婆工作的關係, 我和她遷到了她姊的房子,租一個小房間暫住.

以前我跟老婆常來這裡過夜,但是住下一個星期以後才發現跟以往只是來過夜的情況有很大的不同. 最主要原因是大家的生活習慣不相同,也因為寄人籬下,所以我們要遷就他人,也就沒有以往只有我跟老婆兩人住得那麼舒服了. 再加上老婆常常被她姊罵,有時候聽了也挺難過的. 雖然我也會跟老婆吵架,但是聽到她被我以外的人罵心裡就很不好受.

現在只好將自己的活動範圍僅量縮小, 縮到房間裡就好. 非必要時就不需要到客廳去了,避免不必要的衝突. 寫著寫著怎麼感覺很嚴重, 其實也只不過是因為寄人籬下, 過得沒有以前自在有感而發罷了.

我相信這種情況不會持續太久的.

Thursday, December 1, 2011

Dynamic IP DNS Hosting

Here are the conditions:

1. Client has his own server

2. Client had registered new domain name. (For example, register a new domain name with GoDaddy.)

3. Client server has DYNAMIC IP shared under the router.

 

The solution is pretty simple.

1. Find a FREE DYNAMIC DNS Hosting service.
I use FreeDNS where it provides tons of features and most importantly, it’s FREE!!
clip_image002[5]

 

2. Register a new user with FreeDNS.
Login with username and password after the normal registration procedure.

 

3. Add the registered domain
Go to Domains -> Add Domain

clip_image004[5]

clip_image006[6]
Go to Dynamic DNS, we can see that newdomain.com had been added in!

clip_image008[6]

 

4. Now we have to Register/Modify the NAME SERVER with the vendor that we registered the domain name. (GoDaddy in this case)

There are 4 Name Servers that we need to add in the NAME SERVER list for our domain name.

NS1.AFRAID.ORG (50.23.197.95)
NS2.AFRAID.ORG (174.37.196.55)
NS3.AFRAID.ORG (72.20.15.61)
NS4.AFRAID.ORG (174.128.246.102)

Kindly contact your domain vendor if you don’t know how to modify the Name Server

 

5. When people type newdomain.com in the browser address bar, the domain vendor(GoDaddy in this case) will first get the request and then go to ask the NAME SERVER(FreeDNS in this case) to get the exact IP address of the client’s server.
So now we are going to get the IP address of the client’s server!
Since the client’s server has a DYNAMIC IP address(not fixed, change frequently), we will need a dynamic ip update client here.

 

6. Download the DYNAMIC DNS Client from the list here. I use FreeDNS Update Client in this case.
clip_image010[5]
clip_image012[5]

 

7. The FreeDNS Update Client
clip_image016[5]

Go to Setting and key in the Username / Password, then click the Get Domain List
clip_image018[5]

Finally use a WhoIs service provider to check your domain name. You will get something similar like this if it is successful!
image

Tuesday, November 22, 2011

Get Funding for Start Up

When I had an idea for the start up, I start to search for start up funding similar to Kickstarter and Y Combinator which only support people who possessed US credit card and mailing address. It's a no go for me as I stayed in Malaysia.

Fortunately there is a Cradle Investment Programme (http://www.cradle.com.my/cms/home.jsp) in Malaysia for the head start. Below are some requirement for application.

Looks like I should start finding some partners!





Pre-seed - CIP Catalyst

CIP Catalyst is one of the two pre-seed conditional grants offered by Cradle under the CIP.

The CIP Catalyst which is targeted at entrepreneurs in general, offers conditional grants of up to a maximum of RM150,000 (via two tranches of RM100,000 and RM50,000) to teams of innovative individuals with innovative, technology-based ideas in the ICT, non-ICT and high growth technology industries.

The primary objective of CIP Catalyst is to facilitate the transformation of innovative technology-based ideas from entrepreneurs of all walks of life into commercially viable business enterprises that would in turn spur the growth of an innovative knowledge-based society and economy in Malaysia.

With the CIP Catalyst, recipients are given a 12-month period to complete the development of their prototypes or proofs-of-concept.

Eligibility criteria
Any team of entrepreneurs which meets the following criteria:

  • Main applicant is a Malaysian aged 18 years and above, and
  • Main applicant is permanently residing in Malaysia, and
  • The team comprises a minimum of two (2) members and a maximum of five (5) members per application.
Allowable funding
Categories of funding covered under the CIP Catalyst are broad so that recipients will be able to get all the help needed to develop their innovative ideas. These categories include the:

  • Prototype development
  • Proof-of-concept development
  • Business plans development
  • Purchase of market feasibility research
  • Search and registration of Intellectual Property (IP)
  • Surveys on concrete statistical data
  • Product sampling expenses
Industry Focus
The CIP Catalyst funds the following industries:
  ICT

  • Mobile/wireless tech
  • Creative multimedia & content development
  • Shared services outsourcing
  • Hardware design
  • Software development (Bio-informatics, consumer productivity applications, data mining & business intelligence, electronic design automation, enterprise & business services, gaming & interactive entertainment, Internet & e-Commerce, networking, communications & connectivity, open source, operating systems, security)
  • Internet-based businesses
  Non-ICT
  • Biotechnology (Bio-informatics, Bio-chemicals, Bio-diagnostics tools, agriculture and food tech)
  • Advanced materials
  • Advanced manufacturing-related tech
  • Renewable energy / waste management / recycling tech
  • High-technology consumer & business products
  Others
  • Semi-conductors (manufacturing of integrated circuits, microprocessors, logic devices, chipsets, memory chips)
  • Life sciences (neuroscience, organic chemistry, potential drug target & method of treatment inventions, protein & nucleic acid-based inventions, small molecule chemistry & pharmaceuticals, medical devices, drug delivery systems, molecular biology assays, tools & techniques, analytical chemistry)
  • Clean technology (energy consumption, power management, alternative fuels & materials)
Benefits
As a CIP Catalyst recipient, entrepreneurs will be provided with more than just prototype funding. Recipients will also get value-added services that will help nurture, develop and prepare them to become successful innovators and entrepreneurs, such as:

  • Monitoring of the idea development
  • Mentoring
  • Further funding and market access support
  • Networking opportunities
  • Product and idea refinement
  • Financial training
Application procedure
To apply for the CIP Catalyst grant, follow the steps below:

  1. Visit www.cradle.com.my
  2. Register to obtain your login and password
  3. Once logged on, click on the "CIP Application" tab
  4. In the pop-up box, select Prototype Development
  5. Fill in the online form
  6. Once all information is complete, click SUBMIT
  7. A notification email will be sent to confirm receipt of application
NOTE:
  • All CIP Catalyst applications MUST be submitted online via www.cradle.com.my. Email applications are NOT accepted.
  • If you are unable to complete the form straight away, click SAVE and continue another day when you have all the information at hand.
  • Only click SUBMIT if you have completed the entire form and is ready to submit your application.
  • Applications are processed in batches every month. Batch closing is at end of every month. Applications submitted after the batch closing date will be processed in the following batch.

Monday, November 21, 2011

Going for a Startup

Thinking. A few problems that need to overcome:

1. Idea - A very interesting web application

2. Funding - This is the biggest problem. Find partners?

3. Time frame - Hope to be out in 3 months! Counting from today.

Thursday, November 3, 2011

真的很煩.
真的是很煩.



Monday, October 24, 2011

[轉載] 超級機器人大戰OG 隱藏機體, 武器, 道具入手方式

最近重玩GBA的<<超級機器人大戰OG>>, 從網路上找到一些攻略特此記錄下來. 跟同好一起分享 :D

機體
1. RTX-008L 休基拜恩(ヒュッケバイン008L)
南部響介路線:遊戲中期如果維蕾達離開隊伍時等級達到23級以上,則維蕾達會駕駛本機在第37話“遙遠的故鄉”中作為我方增援登場;
伊達隆聖路線:遊戲中期如果英格拉姆離開隊伍時等級達到32級以上,則林瑪奧會駕駛本機在第37話“黑色幽靈”中登場,過關後得到本機。

2. 瓦爾西昂改(ヴァルシオン改) 
第28話“十字軍消失之日”滿足熟練度的取得條件,過關後得到本機。
  
3. 加利奧(ガーリオン)
在第24話“琉妮、以及瓦爾西奧妮”中使用祐或萊擊墜蕾歐娜,過關後可得到本機。
  
4. 利奧F(リオンF)
在伊達隆聖路線的第16話“激戰斯塔巴克島”中由諒鬥駕駛,作為我方增援登場。

5. 蓋修班斯特R(ゲシュペンストR)
南部響介路線第19話“為了終將到來之日”結束時基利亞姆的等級如果達到23級以上,則他在第31話“假面下的臉是”中會駕駛本機作為我方增援登場。

6. 古倫加斯特(グルンガスト3號機)
南部響介路線,在第30話“背叛的槍口”時擊墜英格拉姆駕駛的R-GUN,並不達成RTX-008L入手的條件,則維蕾達會駕駛本機在第37話“遙遠的故鄉”中作為我方增援登場。

7. 蓋修班斯特Mk-Ⅱ·S(ゲシュペンストMk-Ⅱ·S)
伊達隆聖路線,在第30話“背叛的槍口”時擊墜英格拉姆駕駛的R-GUN,並不達成RTX-008L入手的條件,則本機會在第40話“Insect Cage”時入手。

8. 蓋修班斯特Mk-Ⅱ·M(ゲシュペンストMk-Ⅱ·M)
南部響介路線,在第34話“從過去歸來的亡靈”中作為我方初期配置的機體之一登場。
  

武器
1. 獅子王之刃(シシオウブレード)
第26話“那個男人的真意”過關後熟練度達到23以上,若走的是南部響介路線,則南部響介的擊墜數要在70以上;若走的是伊達隆聖路線,則伊達隆聖的擊墜數要在50以上,過關後得到。

2. 重力砲(グラビトンランチャー)
第31話“假面下的臉是”過關後熟練度達到29以上,所選擇路線的主人公擊墜數在55以上,過關後得到。
  

強化道具
1. 勇者之印(勇者の印)
南部響介路線第34話“從過去歸來的亡靈”過關後雷菲娜的等級在35級以上且熟練度在27以上時入手;
伊達隆聖路線第34話“鋼之巨神”過關後大鐵的等級在35級以上且熟練度在27以上時入手。

2. 鋼之魂(鋼の魂)
南部響介路線第37話“遙遠的故鄉”過關後大鐵的等級在38級以上且熟練度在30以上時入手;
伊達隆聖路線第37話“黑色幽靈”過關後雷菲娜的等級在38級以上且熟練度在30以上時入手。

Sunday, October 23, 2011

Wednesday, October 5, 2011

SELCARE II - Selangor Conference for Alternative & Renewal Energy

Speakers in SELCARE II
Dickson Chan, Dr.Campbell White, Martyn Levy, John Utting (Left to Right)

This conference held in Holiday Villa, Subang Jaya (http://www.holidayvillahotels.com/index.htm) on the 3rd of October, 2011.

Selangor State Government is trying to make a difference by combining
  1. Social and market research,
  2. WIFI CCTV (http://en.wikipedia.org/wiki/Wireless_security_camera) ,
  3. IPTV (http://en.wikipedia.org/wiki/IPTV)
to improve Selangor, to make it a Livable State (http://en.wikipedia.org/wiki/Quality_of_life#Livability).
In short, to create a better living environment in Selangor.

Social and Market Research 
To collect the actual demand from the public, and to ensure that the government pushes the right policies to the public.

WIFI CCTV
This is a very interesting project involving a lot of technologies and money which required a very good and solid network infrastructure.The WIFI CCTV is installed over the network and send surveillance signal to the control room. The person in the control room is able to monitor the CCTVs all over the city.
The monitoring software in the control room can even track a particular person from one cam to another cam similar to what we saw in the movie <> .
Heard that Penang is going to deploy this also. Maybe FREE WIFI in the future?

IPTV
Using the network infrastructure from WIFI CCTV, IPTV could easily be installed for public. The government can then design some survey forms or even send out messages to the public using this IPTV to do a proper and quality survey, to collect feedback from the public.

I'm really looking forward to these technologies to come to Selangor State in the future... We know that the technologies are there, but how the government make use of the technologies is really a question mark. I believe that it's gonna be beneficial to us if they did it properly.

Wednesday, September 28, 2011

New User Guide & Frequently Asked Questions from PHP Development Forum (http://forums.devshed.com)


Disclaimer
This guide is written by ManiacDan and I only copied them down as a reference. All credit goes to him and PHP Development Forum (http://forums.devshed.com).



New User Guide & Frequently Asked Questions

Hello, and welcome to Dev Shed! There are some forum rules you should probably check out in the lounge. This document is designed to replace the old How to Post a Question page and the now-extensive and out of date old FAQ.

Before you even start, there are five things you need to do.

#0 Google for it

Seriously, google it. I guarantee your error-message related questions have been answered. Find the answer. Don't make us type it again.

#1 Read the manual first!

The PHP manual and the MySQL Manual are both very well written. If you want to know how to properly use the PHP function date, don't ask us, read the manual page for date, including the comments on the manual page, which usually include bugs, "gotchas," and usage examples.

How to read the manual:

Let's use the date function as an example.

If we look at manual page (http://www.php.net/manual/en/function.date.php) we see this:

Code:
string date ( string $format [, int $timestamp ] )



The first item is "string." This is the type of variable that is returned by the function. Date() returns a string.

Next is "date": the function name

between ( and ) is a comma-separated list of the arguments the function takes, in the format "type $variable_name"

Any arguments in square brackets are optional.

After the description we then have a parameters section, so for each argument there is a description. On the date page we see "format" with it's description and a very useful reference

Then we see "timestamp" and a description for that - it explicitly tells us that it is optional and what it defaults to

From this information one can start using the function. If you're unfamiliar with it then you should be testing on a test server, reading the error messages, printing debug messages and tweaking your code until it is error free and behaves as intended.

If you have absolutely no knowledge of PHP and MySQL, we'll probably only help you for 5-6 posts before getting frustrated and moving on. Make an effort to learn the languages you're trying to utilize. If it's clear you haven't made an effort to help yourself, we're not going to make any effort to help you.

#2 Understand the situation

The follow items are separate languages and technologies that have nothing to do with each other at the fundamental level:
PHP
MySQL
Regular Expressions
HTML/CSS
JavaScript/AJAX/Jquery

Those items above, when combined properly by a person skilled in all 5 of them, create a fully functioning website. They are NOT the same language, and an expert in one of them is not necessarily an expert in another. Most of the moderators of the PHP boards are experts in all 5 simply through virtue of experience (and being awesome). What most new developers fail to understand is that PHP doesn't "know" anything about your HTML form or your MySQL database. PHP "knows" only PHP things. You must tell it, specifically and explicitly, if you want it to fetch information from a database, or receive information from an HTML form.

Speaking of which, PHP scripts ONLY execute from the moment you click a link until the moment the page is done being displayed. That's all. Scripts can't "wait" for user input, they don't "remember" anything that happened before. Each PHP document is an entirely separate program that has no relation to the OTHER PHP documents on your system. In order to give the impression that your various PHP pages are a cohesive system, you need to make use of cache (APC cache or memcache), databaes, the session, and various other techniques to maintain user flow. You will also have to make sure your HTML output reflects the same styles so the look and feel is maintained. You can do this LATER. Get the PHP working first.

#3 Debug on your own

Debugging a PHP script is easy. If you come to us and say "why won't this script work?" and paste 500 lines of code, we will ignore you. Some of us might even "disagree" with you and remove some reputation from your profile. This is how you debug a PHP script in a very general sense:

0) Know your error types. PARSE errors or SYNTAX mean your PHP isn't valid and has not yet run. Parse errors have nothing to do with your input, database, network, etc. Parse errors will almost always be missing special characters in your code, be they brackets, parens, dollar signs, etc. You will often see parse errors in the format of "UNEXPECTED T_SOMETHING." The tokens (that's why they begin with T) can be found in the manual, but they're normally easy to understand. If you have an unexpected T_STRING, that's a bare string where PHP didn't want one, usually because you've forgotten a semicolon.

FATAL errors mean that your code is broken in such a way that PHP cannot hope to continue. Fatal error messages are even more explanatory than the parse errors, they will normally contain messages like "using a non-object in object context." This means that something you're using as if it was an object is NOT an object. The line number will tell you exactly where you've messed up.

1) By default PHP hides error messages from you (for security reasons). See "FAQ #30: Why do I see a blank screen/page when I visit my PHP script?" (later in this guide) to learn how to enable the display of error messages.

Before asking for help, enable error messages so that you know what is going wrong with your script. PHP will give you a line number and hint as to what's wrong. Fix ALL errors and warnings before you ask a question (unless your question is "what does this warning even mean?"; If that's your question, google it first and read when the last guy asked).

2) Scatter echo statements throughout your code so that you know what's going on. Believe it or not, professional developers making upwards of six figures do this every day. My debugging consists of statements like:
echo __FILE__ . '::' . __LINE__ . ' userId is ' . $userId . "
\n";

Do that as often as you need to until you figure out which portion of your script is causing the issue. Use the var_dump function to dump a variable's contents and datatype, which is handy for boolean values.

3) Check your database connection. If you believe your script is malfunctioning or the database is incorrect, make sure you're doing it right at all. Check the connection information, the username, the password, and the argument(s) to mysql_select_db/mysqli_select_db. When working with MySQLi, you can find further information in the MySQLi-link object's connect_error and error properties. If you've created a "test" database and your script is using THAT while you've connected your PHPMyAdmin to the "real" database, of course it's not working.

4) Ensure you're not using deprecated functionality and that you've fully updated everything. If you're running PHP4, stop reading right now and go fix that. Same with MySQL4 and Apache1. Check the manual page for everything you're using to make sure it's still ok. session_is_registered should not be used. ereg_match should not be used. $HTTP_POST_VARS should not be used. The list goes on and on.

5) See if there's a built-in function to do what you're trying to do. Never write your own implementation of search, sort, reverse, chunk, push, pop, or anything relating to arrays. It's been done. Find it.

6) Have someone look over the code with you. Explain to them how it's supposed to work every step of the way, describe what each line and block are doing. Heck, tell an action figure. I have a Chewbacca bobble head on my desk that I explain bugs to. Simply saying it out loud fixes it half the time.

7) Try your code with other "interferences" removed. If it's a web page, try the code through the command line. If it's a soap service, try it right on the server. If you've written a web/database app that interfaces with a cell phone through ajax and something is broken, you're way too vaue. Build it in pieces, test it in pieces. Nobody puts an entire car together before finding out nothing happens when you turn the key.

8) Use the error reporting built in to your database software. Echoing the mysql_error() return value, the connect_error and error properties of the mysqli link object and the mssql_error() function results will at least tell you what to look for. Note that SQL is a different language than PHP, "Error on Line 1" SQL error messages mean line 1 of your SQL, not line 1 of your PHP script.

#4 Your Question is NOT Urgent

If you believe your question is urgent, if you will fail your class or lose your job if you don't get the proper answer within a specific amount of time, break out your wallet and hire someone. This is a volunteer community that does not respond well to being rushed or scolded.



Bad Questions


Once you've done everything above, it's time to come to the forums and ask for help. The following are the questions that are asked so frequently that we already have answers prepared for you. But first, some BAD questions:

"PHP isn't executing my script properly." -or- "My script is broken." Nonsense, it works just the way you wrote it. You wrote it wrong.

"I've found a bug in PHP." Unless your name is in the list of moderators at the bottom of the forum list, no you have not. In fact, last time I claimed to have found a bug in PHP, I discovered upon further research that it was a very clever feature I hadn't thought about hard enough yet.

"Newbie!!! PLZ HEEEEEELLLPPPPPPP :-( :-(" I wanted to hit myself just for writing that. Use descriptive subject names so we know if we should bother to click or not. A descriptive subject name also helps YOU identify the problem better. "My site don't work" doesn't tell us anything. "cURL failing on HTTPS requests" gives us enough data to click the link, and gives YOU enough thought to maybe google for a solution.

"I tried this code I found and it doesn't work!" That's because the code you found was written for a specific purpose, or may have even been example code that was never intended to work. You can debug it on your own, read it to try to understand it, or use it as a pseudocode study guide for writing your own code fresh. Copy/pasted code will probably never work. Even code you receive in your own threads isn't guaranteed to work. You're not paying anyone for it.

"Please someone write this for me!" No. Go hire someone, we have a whole sub forum for that.


How to Post

#1 Ask how to solve your problem. Do not ask how to implement what you've decided is the solution.

"Help retrieving data from an HTML table on a remote website" is a good thread. "preg_match help" is not. There are 15 other ways to fetch HTML, maybe your way is the wrong one.

#2 Your post title should summarize the problem.

Do not post "Please someone HELP!@!!!!!@#!!!!" Nobody will help you, you'll get a warning, and your thread will be deleted or moved. Make the thread title informative and narrow so that people know exactly what they're getting into.

#3 Use [ CODE ] and [ PHP ] tags where appropriate.

When posting code or plaintext output, wrap the code in [ CODE ] and [ /CODE ] tags (no spaces). Similarly, PHP code should always be wrapped in [ PHP ] and [ /PHP ] tags, that's what keeps the formatting correct and adds automatic coloring. If your code is not indented properly or it's all on one line, you will not receive decent help.

#4 Don't ask for a handout

We're not your employees, your mother, or your teacher. We don't care if you fail your class or lose your job. We're here because we enjoy solving problems and answering questions, not because we're just dying to write a crappy login form for someone. If it's clear you're only asking for us to do your work for you, you'll be ignored. This is a help forum for enthusiasts and professionals who are trying to increase their knowledge of PHP.




Now, on to the real FAQ.

In the interest of keeping this short and unconfusing, any code samples more than 10 lines long will just be called "google for this." In general, for something as easy as these FAQ entries, the google results are good enough.

#1 Why isn’t my form data showing up?
If you have an input called "name" you will need to use $_POST['name'] to access it. Use var_dump($_POST) to examine the contents of the post array if you aren't seeing the proper data. Note that if your form is malformed (ha!) you might not see any data. Inputs must be inside
tags, and the tag must have a proper action and method.

#2 How do I use sessions?
The sessions section of the PHP manual is magnificent. Remember to call session_start() at the top of every page!

#3 Only the first word of my variable is showing up!

For URLs, you need to pass your string through urlencode before you put them into links.

For form fields, remember that HTML tag attributes need to be quoted. WRONG: RIGHT:

#4 I'm using time() in my query, but it's not getting into the table.

PHP's time function is called time(). MySQL's time function is called now(). Remember, PHP and MySQL are different languages.

#5 Why can't I get my variable inside my function?

This is a job for variable scope. Functions don't have access to ANYTHING other than what you pass in (with the exception of super-globals like $_SESSION and $_POST). If you need something inside a function, pass it into the function.

#6 What is "Invalid Result Resource"?
#7 How do I fetch the results from my database query?
#8 When I print the results of my query, all I get is "Resource ID #1"

All of these are related. Recalling that MySQL and PHP are separate languages, what you're actually doing when you query a database is sending a request to a completely different program, which hopefully returns a result, but may return an error, or even die entirely.

There are currently four ways available to access MySQL databases:

The old mysql extension is still heavily in use in a lot of common scripts. Still, its not recommended for use any longer and when creating new script, you should rather chose either MySQLi or PDO. ODBC and the old MySQL extension are just the last alternatives.

When you perform a MySQL query using the old MySQL extension, the result can EITHER be a MySQL result resource, or FALSE. You must check to see if it's false before you attempt to use it. If it's false, the function mysql_error() will return the last error that MySQL gave. The errors returned by this function are identical to the errors you'd get from running that same query on the command line of MySQL directly.

When you echo a MySQL result resource, you simply get the resource's ID. You must use the resource properly with the built-in MySQL functions like mysql_fetch_array.

This is the proper way to handle a MySQL query with the old extension:

php Code:
Original - php Code
  1. $sql = "SELECT name, address, phone FROM people WHERE age > 20";
  2. $result = mysql_query( $sql );
  3. if ( $result === false )
  4. {
  5. echo "ERROR: " . mysql_error();
  6. }
  7. else
  8. {
  9. while ( $row = mysql_fetch_assoc( $result ) )
  10. {
  11. echo "Name: {$row['name']} \n";
  12. echo "Address: {$row['address']} \n";
  13. echo "Phone: {$row['phone']} \n";
  14. }
  15. }


Using the new MySQLi extension, the same can be done either this way:

php Code:
Original - php Code
  1. $sql = "SELECT name, address, phone FROM people WHERE age > 20";
  2. $result = mysqli_query( $returnValueFromConnect , $sql );
  3. if ( ! $result instanceOf mysqli_result )
  4. {
  5. echo "ERROR: " . $returnValueFromConnect->error;
  6. }
  7. else
  8. {
  9. while ( $row = $result->fetch_assoc() )
  10. {
  11. echo "Name: {$row['name']} \n";
  12. echo "Address: {$row['address']} \n";
  13. echo "Phone: {$row['phone']} \n";
  14. }
  15. }


or this way:

php Code:
Original - php Code
  1. $sql = "SELECT name, address, phone FROM people WHERE age > 20";
  2. $result = mysqli_query( $returnValueFromConnect , $sql );
  3. if ( ! $result instanceOf mysqli_result )
  4. {
  5. echo "ERROR: " . mysqli_error( $returnValueFromConnect );
  6. }
  7. else
  8. {
  9. while ( $row = mysqli_fetch_assoc( $result ) )
  10. {
  11. echo "Name: {$row['name']} \n";
  12. echo "Address: {$row['address']} \n";
  13. echo "Phone: {$row['phone']} \n";
  14. }
  15. }


And lastly, this would be one way for doing things using PDO:

php Code:
Original - php Code
  1. $sql = "SELECT name, address, phone FROM people WHERE age > 20";
  2. $result = $pdo->query( $sql );
  3. if ( ! $result instanceOf PDOStatement )
  4. {
  5. echo "ERROR: " . $pdo->errorInfo[2];
  6. }
  7. else
  8. {
  9. foreach( $result as $row )
  10. {
  11. echo "Name: {$row['name']} \n";
  12. echo "Address: {$row['address']} \n";
  13. echo "Phone: {$row['phone']} \n";
  14. }
  15. }


#9 How do I get the auto_increment value of the row I just created?

mysql_insert_id()
mysqli_insert_id()
PDO::lastInsertId()

#10 My data isn't sorting correctly! 10 shouldn't come before 2!

Your data is being stored (and therefore sorted) as TEXT instead of numbers. When you sort strings, they're sorted alphabetically, rather than numerically. 10 comes before 2 just like ba comes before c.

#11 What is the best editor to use for PHP?

Whatever you're comfortable with. PHP can be written enitrely in a plaintext editor like Notepad (though it's not recommended). GEdit, VI, Emacs, Crimson, Eclipse, Notepad++, and many other programs offer syntax highlighting and line numbering. That's really all you need.

#12 Should I use echo or print?

It doesn't matter. Echo is a language construct (so it doesn't get parentheses) while print is a function (so it gets them, and it can return a value). There are many other ways to output text however, including closing your PHP tags and allowing the web server to simply output your raw strings.

#13 I get a parse error on this line, but there's nothing wrong there!

The parse errors given by PHP are given on the line where PHP finally realized there was a problem. Since PHP is a semicolon-delimited language, commands can spread over more than one line. PHP stops when a command stops making sense, which is usually a line or two AFTER the bug. If you forget a semicolon, PHP will complain about the NEXT line.

#14 I need help with this regular expression!

Lucky day for you my friend, we have a whole forum for that.

#15 How do I make my results have pages?

That's called "pagination" and there are so many tutorials out there just begging to be read.

#16 Why am I getting the error "Headers already sent"?

If you try to send a header using the header() function (like for a redirect) and headers have already been sent previously, the call will fail. ANY kind of output will send the plaintext headers, preventing a Location header from being sent. The error message contains the file and line that sent the output. Go there, find the problem, and remove it. Whitespace and Byte Order Markers (BOM) outside of the PHP tags count as output. It's best to remove the closing PHP tag from all your files anyway.

#17 Why doesn't my code work in a specific browser?

We don't know, but it has NOTHING to do with PHP (99% of the time). If you're having problems with forms, var_dump($_POST). If you're having problems with rendering, use firebug, IE developer tools, or chrome inspector to inspect the CSS of the elements that look wrong. If you're having javascript problems, use those tools' javascript consoles to debug your javascript. Post the relevant questions in the appropriate forum, they are not PHP questions.

#18 How do I do this and ignore case?

There's a case-insensitive version of every function. str_replace? str_ireplace. strpos? stripos. strcmp? strncasecmp. etc. View the "see also" section of the function's manual page to find its related functions.

Regular expressions become case-sensitive when you add an "i" at the very end of the string, after the closing delimiter.

#19 I upgraded PHP and now I'm getting all kinds of errors!

Major changes happen with PHP upgrades. Specifically, deprecated features are removed. You may experience problems with register_globals being turned off (meaning any form field names are no longer automatically PHP variables) or existing super-globals (like $HTTP_POST_VARS) disappearing. Turn error reporting all the way up, and walk through your code fixing all the problems. Read the upgrade log next time, too.

#20 How can I have my form fields "remember" on subsequent submit?

Easily! Simply make use of isset() and the PHP ternary operator to give your form field a value only if a specific variable is set:
PHP Code:

echo '. ( isset( $_POST['demo'] ) ? $_POST['demo'] : '' ) . '" />';


#21 How do I set up and configure PHP?

This is generally outside the scope of the actual PHP development forums. XAMPP and WAMP packages are easily available, and the PHP manual has an entire chapter on installation for various operating systems and environments.

#22 How do I do date math?

If you have PHP 5.3 or higher, check out the new DateTime library.

Otherwise, note that PHP can handle timestamps generated by time() and mktime(). Time stamps are integers and they're measured in seconds. To get the time one hour from now, use time() + 3600. You can infer the rest, I'm sure.

#23 How can I perform an action every X times? How can I do alternating row colors? How can I do a 3-column layout?

All of this can be accomplished by modular division. By using the % operator, you can say "do this every X times." If you want alternating row colors...
php Code:
Original - php Code
  1. $rowCount = 0;
  2. foreach( $myData as $record )
  3. {
  4. if ( $rowCount++ % 2 == 0 )
  5. {
  6. $color = "white";
  7. }
  8. else
  9. {
  10. $color = "blue";
  11. }
  12. }


#24 My output is unformatted! I can't see my ! My newlines are gone!

Not true! You're viewing your output in a browser, which is NOT a text viewer. Your browser strips newlines automatically (as it should, since it expects HTML) and converts any tags like into HTML tags, which aren't printed. View the SOURCE of the page to view the actual output.

#25 How can I have a select box populate another select box?

Google for this, it can be done easily with AJAX or with a simple page refresh.

#26 My PHP.ini changes aren't taking effect!

You must be chaning the proper PHP.ini file and you must restart your webserver.

#27 Why can't I use my javascript variables in PHP?

Because as mentioned at the top of this document, PHP and javascript are different languages. Specifically, Javascript won't execute on the same computer that PHP does. PHP executes on your server. Javascript executes on the client machine.

#28 What language should I learn? Why is PHP better than {some other language}?

Requinix covered this in detail in the last version of this FAQ

#29 Why are accented characters displaying incorrectly

If your non-ASCII/non-English/accented/UTF-8/special characters are not showing up, showing up as question marks or block symbols or showing up incorrectly in general, it usually indicates a character encoding problem. You need to make sure you use UTF-8 encoding at every point where your data is transferred or stored. It most cases you should not use the utf8_encode or utf8_decode functions, as these will not do what you need.

(1) Make sure your code editor is set to save all files in UTF-8 mode (without the BOM). All of your .php/.html/.tpl/.css/.js/etc files should be saved using UTF-8. This step is necessary to ensure that the characters stored in your files are encoded consistently.

(2) Make sure your MySQL database character set is set to UTF-8. Depending on your MySql configuration, you might need to configure this for each field individually. Each string field (including text/varchar/char/etc. type fields) in a database table can have an independent character set. This step is necessary to ensure that the characters stored in your MySQL database are encoded consistently.

(3) Make sure your MySQL connection is set to use UTF-8. Do this using the mysql_set_charset, mysqli_character_set_name function or the charset attribute of the PDO dsn (depending on which MySQL interface you're using). You do not need to execute a "SET NAMES" or "SET CHARACTER SET" query, as the mysql_set_charset function handles the necessary queries for you and changes the client charset to the appropriate values. In fact, running these queries manually is not enough, because neither query updates the client charset and you will run into problems. Execute this function as soon as you connect to MySQL (and every time you connect). Your character set needs to be the same when you insert values and when you read values. This step ensures that you're data is transferred between the web server and the database server without the characters becoming corrupted.

(4) When you send output to the browser make sure you tell the browser that it is UTF-8 encoded. There are two ways to do this, but I recommend doing both to be sure:

Send the header:

php Code:
Original - php Code
  1. header('Content-Type: text/html; charset=utf-8');


Use this meta tag:
html Code:
Original - html Code


    ===============================================

    Big thanks to JClasen for updating these examples to the PDO and MySQLi
    __________________
    HEY! YOU! Read the New User Guide

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.