Saturday, October 30, 2010

PHP: How to use multiple combo boxes

At one point or another you will have to generate a separate combo box for each row retrieved from database or just a large sum of combo boxes in general. Creating unique variable names for each combo box is possible but a hassle and a waste of time. Therefor, I present to you an example on how to generate and process multiple combo boxes on the same page.

Here is the code, explanation is below it:

1. Create a form tag with an action to send the script back to the same page and method using POST.
2. Generate as many combo boxes as you like, this examples uses three.
3. Create your submit button and close form tag.
4. Check if submit button has been pressed and use '@' to ignore any errors raised by the statement. Because if the send button isn't pressed you'll get a warning saying $_POST['send'] is undefined or does not exist.
5. If submit test is evaluated to TRUE proceed with looping through array of combo boxes and print the value of each combo box. Here you can do whatever you want with your data.

Before pressing 'OK' each combo box was set to a selection in exactly the same order text is being printed below. Apples, oranges, and grape. Try it yourself.

Saturday, October 23, 2010

PHP: How to exit a for loop or skip iteration

It seems like quite a few people still don't know how to exit various loops. It's really easy and there are two ways you can do this.

First: when you reach a point where you would like to break out of a loop, it would be an if statement most likely just use command "break" to exit the loop. The "break" command just exits the current loop not all loops if you have them nested. This command works with while loops, for loops, and do..while loops.

Second: whenever you reach a point where you would like to exit the loop you can use a "goto" statement to forces jump script another part of the script on the page. To set it up, you place the command "goto goHere" at the point where you want to stop the loop. Then select the area where you would like the script to continue and place "goHere: " statement. Once the script meets your criteria and reaches the "goto" statement it will skip everything and jump to "goHere: " section and proceed from there.

Now, you can also skip loop iterations whenever necessary. Skipping loop iterations is done using "continue" command. This "continue" command does not return anything just skips an iteration and your loop keeps looping as it was before.

Here is an example of all there commands in one script:


As you can see the loop should cycle until $i is less than 100. The iteration is skipped once it reaches 2 and 4. When iteration reaches 5 it forces the script to the last if statement even though variable i does not equal 10 yet. In that if statement we set the variable i to 98 to let the loop finish quickly.

Enjoy!

Friday, October 22, 2010

PHP: file_get_contents() exception handling improved (example)

Here is a straight up example on how to effectively call the function file_get_contents() and properly handle its errors with exception handling.



If you're not familiar with exception handling here is the basic run down.

1. We set the link into $url variable which we want to parse.

2. Using try{} block we test our code for errors.

3. Our variable $page_contents has a symbol '@' in front of it, this symbol ignores any errors raised by that piece of code on that line only.

4. Since function file_get_contents() returns only FALSE when it fails we check our variable $page_contents if it equals to FALSE or not.

5. If the variable $page_contents does in fact equal to FALSE this means function file_get_contents() has failed and we don't want to proceed further. So, the line 14 intentionally throws an error at the script with a predefined message. Unlike other programming languages where errors are caught automatically PHP requires this to be done manually.

6. Catch{} block is responsible for catching any errors thrown at it by the try{} block. Catch{} block will handle errors as it is defined, in our case it's just printing the error message.

Exception class itself is quite big and you can modify it to catch different types of errors so dig in and explore.

Post some feedback if you got it working. Enjoy!

Wednesday, October 20, 2010

PHP: flush and ob_flush example - print output to browser

UPDATE (June 4, 2011): After writing a parsing script in PHP I stumbled on a bad coding technique which kept crushing my script along with the browser (Firefox). This problem was noticed after running my script for longer than an hour. The real problem is not in time it took the script to execute but the amount of output being printed to the screen.

Problem: by using ob_flush() and flush() functions alone the script kept building the buffer size until it reached its peaked and crushed the browser.

Solution: After using echo commands to print your text use ob_get_contents() function to print whatever you have in the buffer. Then, use functions flush() and ob_flush() to discard the buffer. Keep in mind, ob_flush() does not destroy your buffer. Lastly, call the function ob_end_clean() to clean your buffer and start fresh.

Example:
ob_get_contents();
flush();
ob_flush();
ob_end_clean();

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

The function flush() and ob_flush() are suppose to refresh the screen while the script is still working by outputting buffer to the browser. There are quite a lot of conditions to meet for each browser to make these functions work.

Here is how to make function flush() work without having to modify browser settings:



That's all there is to it. Just run 6 functions consecutively and your buffer will be printed to the screen.

As you can see, the page is still loading but the output is being printed on the screen every 3 seconds. This example uses Mozilla Firefox.

Monday, October 18, 2010

PHP Basics: Your first script/web page

The first and main reason why I like PHP so much is because of its flexibility. There is no need to define, cast, convert variable types all the time. PHP does it for you automatically which makes it so easy to work with.


To continue the following basic tutorial you have to make sure PHP is installed on your machine along with virtual host. Personally, I use EasyPHP. One file, one installation and everything is up and running. Also, make sure you're familiar with basic HTML syntax.


Step 1: Create a file page_one.php in your www folder (or wherever your working localhost directory is).


Step 2: Copy this code from text area into your file and save.



Step 3: Launch the file in your browser. The output you will get is:

My first page


< ?php ?> - These are opening and closing tags for the browser to identify where PHP syntax begins and ends.
echo - Echo statement is used to print information on the page.

Saturday, October 16, 2010

PHP: How to print/echo object properties

When you're in the process of writing code occasionally you will save your work and run the script to see what you have so far. This generally works if you're working with basic variables and arithmetic but when it comes down to arrays and objects the programmable way would be to use foreach or for loop to get results printed on the page.

Well, there is an easier way to get what you want. To print data of your array use this approach and you'll know the contents of your array and multi-dimensional array
$array[0] = "1";
$array[1] = "2";
$array[3] = "3";
print_r($array);


After you launch the script, right click the page and select View Source. The result:

Array
(
     [0] => 1
     [1] => 2
     [2] => 3
)

Use the same approach to print your object properties quickly:
class Sample{
public $example = 5;
}

$test = new Sample();
print_r($test);


The output for object properties is:
Sample Object
(
     [example:Sample:public] => 5
)

Making testing easier one step at a time.