Latest Posts

Tips: Textarea accepts New line ( \n )

The <textarea> tag defines a multi-line text input control.
A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).
The size of a textarea can be specified by the cols and rows attributes, or even better; through CSS' height and width properties.

<textarea name="products" cols="23" rows="3"></textarea>


 OUT PUT


 Test First Line

New Line



 $products = str_replace("\n", "<br>", $_POST['products']);


   Parameter :  str_replace("search", "replace",  $content);


note: str_replaceReplace all occurrences of the search string with the replacement string

read more...

ECCP Official Website


The European Chamber of Commerce of the Philippines (ECCP) is a service-oriented organization whose main goal is to foster close economic ties and business relations between the Philippines and Europe. The ECCP does this by providing a wide range of business services and by creating linkages between companies, organizations and individuals with existing or potential business interests in Europe and the Philippines.


Design and Program by: Chi Calicdan & Willbert Ng


Back End: PHPOctopus (inHouse CMS by: ECCP)
  • PHP
  • MySQL
  • JQuery
  • CSS
Front End : 
  • PHP5
  • MySQL
  • JQuery (FancyBox, Nivo Slider, Alexfish Listticker and more..)
  • CSS
  • Ajax Pagination (by: Chi Calicdan)
read more...

Sort Time & Date inside a multidimensional array()

uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function. .


function mysort($a, $b)
{
   return(strtotime($b['timestamp']) - strtotime($a['timestamp']));
}


// Convert first date & time to UNIX timestamp

$t1 = mktime(2, 30, 0, 7, 1, 2011);
$t2 = mktime(3, 30, 0, 7, 1, 2011);
$t3 = mktime(4, 30, 0, 7, 1, 2011);


// Store data to a Multidimensional Arrays
$testArray = array(
    "testing3" => array("timestamp" => $t1, 
                        "name" =>"testing3"),
                         
    "testing" => array("timestamp" => $t2, 
                       "name" =>"testing"),
                        
    "testing2" => array("timestamp" => $t3, 
                        "name" =>"testing2")
    );
                          


usort($testArray, 'mysort');

echo "<pre>";
print_r($testArray);

echo "<br /><br />";

foreach($testArray AS $row){
 
 $date = $row['timestamp'];
 echo date("d/m/y : H:i:s a",$date)."<br />";
}

OUTPUT
Array
(
    [0] => Array
        (
            [timestamp] => 1309519800
            [name] => testing2
        )

    [1] => Array
        (
            [timestamp] => 1309516200
            [name] => testing
        )

    [2] => Array
        (
            [timestamp] => 1309512600
            [name] => testing3
        )

)


01/07/11 : 04:30:00 am
01/07/11 : 03:30:00 am
01/07/11 : 02:30:00 am
read more...

Php: ARRAY Tips & Tricks

What is an Array?

An array is a like a list or a group of similar elements which stores data of a specific data type. These data elements are stored in a series inside the array and each of these stored data element has its own position in the Array by which it is referred to and retrieved. The position of these stored elements is maintained by the Index of the Array which is usually made up of consecutive integers beginning at zero. The values which are used to index the elements in an array are unique. That means, you can have only one unique value as an indexer (Key) and no two data elements in an array will have same indexer or the key.

Types of Arrays in PHP

Numerical or an Indexed Array, the indexer of the array which is used to determine the position (also known as Key) of the stored data element is an integer which begins at zero.


Position in     Array Name
        0 => TCP
        1 => IP
        2 => DNS

Associative array, the key or the indexer of the array which is used to refer to the data element is a string and not an integer.

Abbreviation     Expanded Term
      TCP    =>    Transmission Control Protocol
         IP    =>     Internet Protocol
       DNS  =>     Dynamic Naming System

Multidimensional arrays can become confusing, as they are more complex than numerical and associative arrays. Think of multidimensional arrays as a book. Each array is a chapter and a “subarray” is a page number within that chapter. Remember, a multidimensional array can contain more than one array within itself.

An example of a multidimensional array can look like:


$colors = array(
             array(“black”, gallons , quarts , liters),
             array(“white”, gallons , liters),
             array(“yellow”, gallons , quarts , liters)
          ); 

To associate a multidimensional array as a book, the array “colors” is the name of the book. The arrays “black”, “white” and “yellow” are chapters in the book, and “gallons”, “quarts” and “liters” represent page numbers within each chapter.

Notice that each subarray can have its own values which do not have to be the same as other subarrays. Also, each value within a subarray ends with a comma except the last value within the subarray. This is important to keep in mind, otherwise this multidimensional array will not work.


 $myLists['colors'] = array("apple"  => "red",
                            "grass"  => "green",
                            "sky"    => "blue",
                            "night"  => "black",
                            "wall"   => "white");                      
  
  $myLists['cars'] = array("BMW"     => "M6",
                           "Mercedes"=> "E 270 CDI",
                           "Lexus"   => "IS 220d",
                           "Mazda"   => "6",
                           "Toyota"  => "Avensis");                      

//To access and display an element in the multidimensional array 
//you just extend the key list as follows:

echo $myLists['cars']['Toyota'];


Array Operations in PHP

Split an array into chunks

To split an array into smaller chunks or smaller sized arrays, we use array_chunk() function of PHP. This will return arrays of several smaller sizes and each array's index number will start with zero unless you want to use the preserve_keys parameter to preserve the original index numbers from the input array used.

$my_array = array("One", "Two", "Three", "Four");
$split_array = array_chunk($my_array, 2);
print_r($split_array);

OUTPUT :
Array
(
    [0] => Array
        (
            [0] => One
            [1] => Two
        )

    [1] => Array
        (
            [0] => Three
            [1] => Four
        )

)

Combine an array with data elements and other with its keys

We can create an array by combining one array with keys and second array with corresponding data elements. Note that the number of keys and data elements in both the arrays has to be equal for this operation to be successful. We will make use of built-in function array_combine().


$keys_array = array(1,2,3,4);
$data_array = array("one","two","three","four");
$new_array = array_combine($keys_array, $data_array);

print_r($new_array);

OUTPUT
Array ( [1] => one [2] => two [3] => three [4] => four )

Merging two or more arrays

$first_array = array(1,2);
$second_array = array(3,4);
$third_array = array(5,6);

$merged_array = array_merge($first_array,$second_array,$third_array);

print_r($merged_array);

//OUTPUT
//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

Searching for a value in an array

$months = array(1=>"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug",
                    "Sep", "Oct", "Nov", "Dec");

$key = array_search("May", $months); //Searching for May in months array

echo $key;
// We can also print the value that key points at

echo $months[$key];

//OUTPUT:  5 May

Find Value

in_array(search word, array) is a function very useful while working with arrays, especially for filtering certain items. Using this function you can find easily a value.

See the example:
$fruits = array("apple","orange","strawberry");

if(in_array("apple", $fruits))
{
    echo "Apple is in the array"
}
else
{
   echo "Apple is not in the array";
}

Validate if ARRAY

$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';


Count Array
$fruits = array(1 => "apples",2 => "oranges",3 => "bananas");

$total_elements = count($fruits);

OUTPUT: 3

Get ODD and EVEN value of an Array

function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));

echo "Even:\n";
print_r(array_filter($array2, "even"));


SPLIT ARRAY ID TO LEFT AND RIGHT VALUE

echo $string = '1|2,1|3,1|4';
           
$e = explode(',',$string);
           
$left = array();
$right = array();
           
foreach($e as $v){
 list($l,$r) = explode('|', $v);
$left[] = $l;
              $right[] = $r;
}

//---you can also do this
foreach($e as $v){
            list($left[],$right[]) = explode('|', $v);
}

           

print_r($left);
print_r($right);

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



NOTE: HERE’S THE COMPLETE LIST OF ALL ARRAY FUNCTIONS 
http://www.nusphere.com/kb/phpmanual/ref.array.htm

read more...

Common PHP mistake

Untitled Document

These are some very common mistakes that are made in PHP. Some of these can be tricky to catch and can lead to all sorts of strange behavior. So here are common PHP coding mistakes to avoid.

1. '=' Vs. '= ='
Using a single '=' in a comparison will cause an assignment and return true, so this mistake can have some pretty unexpected results. It can be hard to catch since it looks perfectly valid to the interpreter if you are comparing something with a variable.
$x = 3; // value of x is now 3
$x == 4; // false. == compares the value of y to x

2 '= =' Vs. '= = ='
There is a big difference between the '= =' (equal) and '= = =' (identical) comparison operators. '= =' will convert types to match before making the comparison, while '= = =' will compare directly without converting. So in situations where the difference between '0' and 'false' matters, you must use '= = ='. Here's some examples:
var_dump(false == 0); // true
var_dump(false === 0); // false
var_dump(false === false); // true
var_dump('0' == 0); // true
var_dump('0' === 0); // false


3 Missing Quotes Around String Keys
When working with arrays with string keys, it is important to quote literal strings. Without quotes, PHP will look for a constant with that name, then convert to string when none is found. Usually this is just a minor performance hit, but it can lead to unexpected results if the constant does happen to exist.
 
define('foo', 'bar'); // constant foo is 'bar'
$array = Array('foo' => 'This is foo', 'bar' => 'This is bar');

// BAD
var_dump($array[foo]); // 'This is bar'
 
// GOOD
var_dump($array['foo']); // 'This is foo'
?>


4 Mismatched Quotes or Braces
A common mistake that leads to many syntax errors is mismatched quotes or braces. Some things to remember:
* For every ' there's a '
* For every " there's a "
* For every ( there's a )
* For every { there's a }
* For every [ there's a ]

5 Missing ';'
PHP requires that each statement ends with a semicolon so that it knows where one instruction ends and the next begins. Omitting a ';' will cause PHP to treat everything up to the next ';' as one statement. This usually results in a syntax error (usually from the next line).

6 Misplaced ';'
An extra semicolon can be just as bad as omitting one. Control structures like if and while should not end with a semicolon. Doing so will effectively cause PHP to ignore the results and simply execute the code found in the block, treating it as an empty statement.

The above outputs 'something is wrong' because the if statement is completely ignored.


7. Setting Headers After Output

You can't modify headers once you send them to the client. This means that as soon as any output is sent to the browser, you can't use header, session_start, setcookie, or any other functions that modify headers. You can use the headers_sent function to determine if headers have been sent.
In most cases, this mistake is made when rogue white-space exists at the end of an included file. An easy way to avoid this is to omit the closing "?>" tag in your includes.

8. Using Short Tags

You should always use "<?php" and "?>" around your PHP blocks for portability. Using the convenient short and alternative tags ("<?", "<?=", and "<%") is not supported by default and should be avoided.

9. Using 'ereg*' Functions

As of PHP 5.3, the POSIX (ereg*) family of regex functions have been deprecated, and will be removed in PHP 6. This isn't really a big deal right now, but you should move away from these to future-proof your code. You should instead use the PCRE (preg*) family of functions.
10 Not Using E_ALL During Development

The best way to avoid the majority of mistakes is to turn error reporting all the way up in development. This will tell you about all the little things that can potentially lead to problems. If you can write code that produces no errors under this condition, you are probably good to go!


10. Missing Dollar Signs '$'

A missing dollar sign in a variable name can be easy to miss. PHP will usually give you a parsing error if you have one, or at the very least your script won’t work.


11. NOT Using database caching

If you're using a database in your PHP application, it is strongly advised that you at least use some sort of database caching. Memcached has emerged as the most poplar caching system, with mammoth sites like Facebook endorsing the software.
Memcached is free and can provide very significant gains to your software. If your PHP is going into production, it's strongly advised to use the caching system.

12.Not Using E_ALL Reporting

Error reporting is a very handy feature in PHP, and if you're not already using it, you should really turn it on. Error reporting takes much of the guesswork out of debugging code, and speeds up your overall development time.

While many PHP programmers may use error reporting, many aren't utilizing the full extent of error reporting. E_ALL is a very strict type of error reporting, and using it ensures that even the smallest error is reported. (That's a good thing if you're wanting to write great code.)


13. Not Setting Time Limits On PHP Scripts
When PHP scripts run, it's assumed that they'll eventually finish in a timely manner. But every good programmer knows that nothing should be assumed in a piece of code. Nothing makes a program crankier than an unresponsive script.
You can get around this issue by simply setting a time limit on the script (set_time_limit). While it may seem like a trivial thing, it's always clever to prepare for the worst.

14. Not Protecting Session ID's

A very common PHP security mistake is not protecting session ID's with at least some sort of encryption. Not protecting these Session ID's is almost as bad as giving away a user's passwords. A hacker could swoop in and steal a session ID, potentially giving him sensitive information. MT Soft an example of how to protect Session ID's with sha1:
view plaincopy to clipboardprint?

if ($_SESSION['sha1password'] == sha1($userpass)) {   // do sensitive things here 

} 
if ($_SESSION['sha1password'] == sha1($userpass)) {   // do sensitive things here

}

Adding the shai1 to the ($userpass) gives an added bit of security to the session. Sha1 isn't a bulletproof method, but it's a nice barrier of security to keep malicious users at bay.

15. Not Validating Cookie Data

How much trust do you put into cookies? Most people don't think twice about the seemingly-harmless bit of data that's passed by a cookie. The name "cookie" itself is associated Milk, nap time and Santa, for crying out loud! How could a cookie possibly harmless?

If you're not validating cookie data, you're opening your code to potential harmful data. You should use htmlspecialchars() or mysql_real_escape_string() to validate the cookie before storing it in a database.



Reference :
http://www.ultramegatech.com/blog/2009/11/10-common-php-mistakes-to-avoid/
http://net.tutsplus.com/articles/are-you-making-these-10-php-mistakes/
read more...

Php Code Optimization tips

1.    Use static methods when possible, this is 4 times faster
2.    Echo is faster as print
3.    Use , instead of . to concatenate a string
echo "Hello", $world;
echo "Hello" . $world;
4.    Set the max value in a for-loop before the loop, not in the if statement.
$max = count($array);
for ($i=0;$i<$max;$i++) 
{ 
    echo $i;
} 
5.    Unset vars to clear memory (especially when using arrays)
6.    Use full paths in includes and requires, so the server doesn't have to resolve the paths for you
7.    Use strncasecmp, strpbrk and stripos in stead of regex
8.    “else if” statements are faster than select statements aka case/switch
9.    Suppress errors with an @ is very slow
10.    Close database connections when you don't need them anymore
11.    $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.
12.     Wrap your string in single quotes (') instead of double quotes (") is faster because PHP searches for vars in "..." and not in '..'
13.    A PHP script is 2 to 20 times slower as a HTML page. Use HTML pages when possible.
14.    PHP scripts are compiled every time you call them. Use PHP caching software to gain a speed optimization of 25% to 100%.
15.    $i++ is slower as ++$i
16.    Not everything has to be OOP. Most of the time OOP is just overhead, so use it wisely!
17.    Use as much of the default functions of PHP, you don't have te reinvent the wheel!
18.    Turn on error_reporting(E_ALL | E_STRICT); in development.
read more...

10 things you (probably) didn’t know about PHP [Re-Post]

PHP is simultaneously the most infuriating and joyful languages I’ve ever worked with. I say “infuriating” primarily because the function names are so inconsistant. Despite the fact that I use it almost everyday, I still have to think to myself “Is it str_pos or strpos? str_split or strsplit?” On the other hand, occasionally I’ll stumble across a gem that perfectly solves the problem at hand with a single line of code.
Here’s a short list of cool features that might have slipped under your radar as well:
  1. Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit).
  2. Partially validate email addresses by checking that the domain name exists with checkdnsrr(). This built-in function checks to ensure that a specified domain name resolves to an IP address. A simple user-defined function that builds on checkdnsrr() to partially valid email addresses can be found in the user comments section in the PHP docs. This is handy for catching those occasional folks who think their email address is ‘joeuser@wwwphp.net’ instead of ‘joeuser@php.net’.
  3. If you’re using PHP 5 with MySQL 4.1 or above, consider ditching the mysql_* functions for the improved mysqli_* functions. One nice feature is that you can use prepared statements, which may speed up queries if you maintain a database-intensive website. Some benchmarks.
  4. Learn to love the ternary operator.
  5. If you get the feeling that you might be reinventing the wheel during a project, check PEAR before you write another line. PEAR is a great resource that many PHP developers are aware of, yet many more are not. It’s an online repository containing over 400 reusable snippets that can be dropped right into your PHP application. Unless your project is trully unique, you ought to be able to find a PEAR package that saves at least a little time. (Also see PECL)
  6. Automatically print a nicely formatted copy of a page’s source code with highlight_file().This function is handy for when you need to ask for some assistance with a script in a messageboard, IRC, etc. Obviously, some care must be taken not to accidently show your source when it contains DB connection information, passwords, etc.
  7. Prevent potentially sensitive error messages from being shown to users with the error_reporting(0) function. Ideally error reporting should be completely disabled on a production server from within php.ini. However if you’re on a shared webhost and you aren’t given your own php.ini, then your best bet is to add error_reporting(0); as the first line in each of your scripts (or use it with require_once().) This will prevent potentially sensitive SQL queries and path names from being displayed if things go awry.
  8. Use gzcompress() and gzuncompress() to transparently compress/decompress large strings before storing them in a database. These built-in functions use the gzip algorithm and can compress plaintext up to 90%. I use these functions almost everytime I read/write to a BLOB field within PHP. The only exception is when I need full text indexing capabilities.
  9. Return multiple values from a function with “by reference” parameters. Like the ternary operator, most PHP developers who come from a more formalized programming background already know this one. However, those who’s background is more HTML than Pascal, probably have wondered at one time “how do I get multiple values back from a function I wrote, even though I can only use one return value?” The answer is that you precede a variable with “&” and use it “by reference” instead of “by value”.
  10. Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it’s absolutely critical to understand. If you’ve never heard the term before, spend the entire rest of the day googling and reading.
[Re-Post]: http://www.rightbrainnetworks.com/blog/10-things-you-probably-didnt-know-about-php/
read more...

PHP: Date Computation [add-minus]

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.
Tip A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.


Here's some sample tips to calculate DATES in PHP. 
echo date("Y-m-d");
echo date("Y/m/d");
echo date("M d, Y");
echo date("F d, Y");
echo date("D M d, Y");
echo date("l F d, Y");
echo date("l F d, Y, h:i:s");
echo date("l F d, Y, h:i A");

Output
2010-11-30 
2010/11/30 
Nov 30, 2010 
November 30, 2010 
Tue Nov 30, 2010 
Tuesday November 30, 2010 
Tuesday November 30, 2010, 05:58:37 
Tuesday November 30, 2010, 05:58 AM

Calculate Date range of  Start Date and End Date   
$startDate = "11/20/2010"; 
function get_diff_date($target, $today) {

$splitStart = explode("-",$target);    
$splitEnd   = explode("-",$today);    
   
//m-d-y  
$target = mktime(0,0,0,$splitStart[1],$splitStart[2],$splitStart[0]);  
$today  = mktime(0,0,0,$splitEnd[1],$splitEnd[2], $splitEnd[0]);    
    
$difference =($target-$today) ;
$days =(int)($difference/86400) ;
 
    return $days;
}


$today   = date('Y-m-d');
$endDate = "2010-12-29";

$days = get_diff_date($endDate,$today);

print "Our event will occur in $days days";

//OUTPUT : Our event will occur in 28 days 


Definition and Usage

The mktime() function returns the Unix timestamp for a date.
This timestamp contains the number of seconds between the Unix Epoch
(January 1 1970 00:00:00 GMT) and the time specified.

Syntax :

mktime(hour,minute,second,month,day,year,is_dst) 


ADD  MINUS from Current Date

$var = 1; //change value 
$tomorrow  = mktime (0,0,0,date("m") ,date("d") + $var,date("Y")); 
$lastmonth = mktime (0,0,0,date("m")- $var,date("d"), date("Y"));  
$nextyear  = mktime (0,0,0,date("m"), date("d"), date("Y") + $var); 


echo "Tomorrow :  ". date("m/d/Y", $tomorrow);  
echo "Last Month: ". date("m/d/Y", $lastmonth); 
echo "Nexy Year:  ". date("m/d/Y", $nextyear);  

OUTPUT
Tomorrow  : 12/01/2010
Last Month: 10/30/2010
Nexy Year : 11/30/2011

TRICKS on DATE RANGE
-Use range();
$currentYear = date("Y"); 
$years = range($currentYear, 2005); 

  foreach ($years as $value) {
    echo $value ."-";
  }

OUTPUT:  2010 - 2009 - 2008 - 2007 - 2006 - 2005

[ you can also use : range(); ]
$letter = range("a","d");
print_r ($letter);

Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

read more...

Basic Query

COMING SOON.....
read more...