12/26/2012

PHP swap two variables

Some ways for swapping two variables

1. temporary variable
    $a = 100;
    $b=200;
    $tmp = $a;
    $a = $b;
    $b = $tmp;


2. list
    $a = 100;
    $b=200;
    list($b,$a) = array($a,$b);

3. XOR
    $a = 100;
    $b=200;

    $a = $a  ^ $b;
    $b = $a  ^ $b;
    $a = $a  ^ $b;

   or
       $a = $b  ^= $a ^=  $b;


Note
  1.  The ways 1 and 2 can be used for any variable, including array, object, etc.
  2. The way 3 can not be used on array, object.


   

PHP ternary operator

There are some ternary operators in PHP language.

1. if ... else
   if($a==1){
     echo 'good';
   }
   else{
     echo 'error';
   }

   ==>
echo    ($a==1)? 'good': 'bad';

2. AND

   if($a==1) echo 'good';

  ==>
  ($a==1) AND  print( 'good';)

12/25/2012

Difference for Delete Table and Trncate Table - MySQL

Difference for Delete TABLE and Truncate TABLE

Delete TABLE VS Truncate TABLE


In order to remove all data from one table, you may use delete or truncate command. Just like

Syntax
Truncate [TABLE] table_name;

Delete [LOW_PRIORITY] [QUICK] [IGNORE] FROM table_name
          [ WHERE  where_condition]
          [ORDER By .....]
          [LIMIT row_count]
e.g.
Delete FROM table_name;

Truncate FROM table_name;

But there are some difference for them.

1. Speed
  Truncate is faster than Delete.
  Truncate will drop table and create a new table for you. Delete will just remove all data, but not table.

2. Return Value
   Truncate will return 0 because it remove the table
   Delete will return the number of removed rows.

3. Increment primary key (MyISAM Table)
   Truncate will clear the increment key to 1.
   Delete will not influence the increment key. 
  E.g.  If the last increment key was 1000, the next inserted record key after Delete will be set to 10001, on the contrary, the new key after Truncate will be set to 1.

4. Remove parts of records or Where Clause
   Truncate will all data
   Delete can remove parts of records based on Where clause.
   E.g. Delete FROM table_name WHERE id BETWEEN 100 AND 1000;

5. Language
    Truncate is DDL (Data Definition Language).
    Delete is DML (Data Manipulation Language).

6. Restore data
    you nay use rollback to restore data after you execute Delete command
    You can not restore the data after you execute Truncate command


All data will be lost permanently after you execute truncate or delete clause. So, please remember to check all data before you remove all data.