Sunday, 30 October 2011

PHP Reference Sheet (Basics)


Data Types
integer, float, boolean, string, array, object, resource, NULL

Variable Declarations
$variablename = <value>;
$anothervariable =& $variablename; (Assign by Reference)

Declare Array
$arrayname = array();

Initialize Array
$arrayname = array(<value1>, <value2>, <value3>);
$arrayname = array(<key> => <value>, <key> => <value>); (Define Keys)
$multiarray = array(<key> => array(<value1>,<value2>)); (Multi-dimensional)

Common Array Functions
sort(<array>); (Sort array assigns new keys)
asort(<array>); (Sort array maintain keys)
rsort(<array>); (Sort array in reverse, new keys)
arsort(<array>); (Sort array in reverse, maintain keys)
count(<array>); (Count elements)
count(<array>,COUNT_RECURSIVE); (Count multidimensional array)
array_push(<array>,<value>); (Push item onto end of array)
array_pop(<array>); (Pop item off end of array)

Comments
// Comment text
/* Multi-line comment text */
# Comment text

Arithmetic Operators
+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)

Relational Operators
== (Equal), === (Equal with type comparison), != (Not equal), <> (Not equal), !== (Not Equal with type comparison), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to)

Logical Operators
! (logical NOT), && (logical AND), || (logical OR), xor (logical XOR)

Assignment Operators
= (Assign), += (Addition), -= (Subtraction), *= (Multiplication), /= (Division), .=
(Concatenation), %= (Modulus), &= (And), |= (Or), ^= (Exclusive Or), <<= (Left Shift), >>=(Right Shift)

String Concatenation
. (Period)


String Manipulation
substr(<string>,<start>,[<length>]);
strlen(<string>);
trim(<string>);
ltrim(<string>); // Trim left
rtrim(<string>); // Trim right
strtolower(<string>);
strtoupper(<string>);
str_replace(<search>,<replace>,<string>,[<count>]);
strpos(<string>, <search>);
strcmp(<string1>,<string2>); (Binary safe string comparison)
strcasecmp(<string1>,<string2>); (Binary safe case-insensitive comparison)
explode(<delim>,<string>,[<limit>]); (Break string into array)
implode(<delim>,<array>); (Join array into string separated by delim)

Cookies
setcookie (<cookiename>, [<value>],[<expire_time_in_secs_since_epoch>]);
$_COOKIE['cookiename']; (Returns value of cookie)

Sessions
session_start(); (Create session)
$_SESSION['key_name'] = value; (Set session variable)
$variablename = $_SESSION['key_name']; (Retrieve value from session variable)
session_destroy(); (Destroy session)

Error Handling
try {
<statements that may cause error>;
}
catch (<Exception Class> $exception_name)
{
<statements to execute when error is caught>;
}

Super Globals
$GLOBALS (Access all global variables in script)
$_SERVER (Access web server variables)
$_GET (Values passed to script through URL)
$_POST (Values passed to script through HTTP Post)
$_COOKIE (Values passed by user cookie)
$_FILES (Values passed by HTTP Post File Uploads)
$_ENV (Values passed to script via the environment)
$_REQUEST (Values passed by URL, HTTP Post, or user Cookies)
$_SESSION (Values passed through user's session)

If Else
if (<condition 1>)
{ <statement 1>; }
elseif (<condition 2>)
{ <statement 2>; }
else
{ <statement 3>; }

Inline If (Ternary)
<condition> ? true : false;

For Loop
for (<initialize>;<condition>;<update>)
{
<statements>;
}

For Each Loop
foreach (<array> as [<value> |<key> => <value>])
{
<statements>;
[break];
[continue];
}

While Loop
while (<condition>)
{
<statements>;
}

Do-While Loop
do
{
<statements>;
} while (<condition>);

Switch
switch (<expression>)
{
case <literal or type>:
<statements>;
[break;]
case <literal or type>:
<statements>;
[break;]
default:
<statements>;
}

Function Structure
function <function_name>([<parameters>])
{
<statements>;
[return <value>;]
}

Class Structure
class <class_name> [<extends base_class>]
{
[var | <modifiers*>] [<class member variables>];
[<modifiers*>] function <function_name>([<parameters>])
{
<statements>;
}
}
* Modifiers <public | pr ivate | static> are implemented in PHP5

Declare and Use Class
$variable = new class_name();
$variable->function_name();
class_name::function_name(); (Static call)


Thanks!!!!!!!!!! Enjoy Programming :)

Sunday, 23 October 2011

Why GROUP_CONCAT returns BLOB?

Last week, when using the GROUP_CONCAT() function on a MySQL database, I got an unexpected result. :(

Indeed, instead of getting my result as VARCHAR types, I got it as BLOB types! For information, a BLOB is a binary large object that can hold a variable amount of data:
http://dev.mysql.com/doc/refman/5.0/en/blob.html
Because BLOB values are treated as binary strings, it is not easy to use. This is why we would prefer to have VARCHAR values.

So the question is how to get around this frustrating problem?

The answer is, for once, very simple! :D
You simply need to:

Open your my.ini or my.cnf file;
Change the value of the group_concat_max_len system variable to 512 (no ‘k’ suffix);
Restart the mysql service

To verify if the value has been successfully updated, execute the following command in your mysql client:
mysql> show variables like "%concat%";
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| group_concat_max_len | 512 |
+----------------------+-------+
1 row in set (0.00 sec)

Note that you cannot set the value of group_concat_max_len to less than 1Kb using the MySQL Administrator GUI. Which means that the only way to set this system variable to 512 (which is less than 1Kb) is to edit your MySQL configuration file as described above.

Sunday, 16 October 2011

Different type of Cookies?

What are Temporary Cookies?

Temporary, or session, cookies are removed from your computer after you close the browser. Websites use them to store temporary information, such as items in your shopping cart.

 What are Persistent Cookies?

Persistent, or saved, cookies remain on your computer after you close the browser. Websites use them to store information, such as your sign-in name and password, so that you don't have to sign in each time you go to a particular site. Persistent cookies can remain on your computer for days, months, or even years.

What are First-party Cookies?

First-party cookies come from the website that you're viewing and can be either persistent or temporary. Websites might use these cookies to store information that they'll reuse the next time you go to that site.

What are Third-party Cookies?

Third-party cookies come from other websites' advertisements (such as pop-up or banner ads) on the website that you're viewing. Websites might use these cookies to track your web use for marketing purposes.



Saturday, 15 October 2011

Cloud Computing vs. Virtualization

Cloud computing and virtualization are both technologies that were developed to maximize the use of computing resources while reducing the cost of those resources. They are also mentioned frequently when discussing high availability and redundancy. While it is not uncommon to hear people discuss them interchangeably; they are very different approaches to solving the problem of maximizing the use of available resources. They differ in many ways and that also leads to some important considerations when selecting between the two.

Virtualization: More Servers on the Same Hardware


Virtualization

It used to be that if you needed more computing power for an application, you had to purchase additional hardware. Redundancy systems were based on having duplicate hardware sitting in standby mode in case something should fail. The problem was that as CPUs grew more powerful and had more than one core, a lot of computing resources were going unused. This obviously cost companies a great deal of money.


Enter virtualization. Simply stated, virtualization is a technique that allows you to run more than one server on the same hardware. Typically one server is the host server and control the access to the physical server’s resources. One or more virtual servers then run within containers provided by the host server. The container is transparent to the virtual server so the operating system does not need to be aware of the virtual environment. This allows server to be consolidated which reduces hardware costs. Less physical servers also means less power which further reduces cost.

Most virtualization systems allow the virtual servers to be easily moved from one physical host to another. This makes it very simple for system administrators to reconfigure the servers based on resource demand or to move a virtual server from a failing physical node.

Virtualization helps reduce complexity by reducing the number of physical hosts but it still involves purchasing servers and software and maintaining your infrastructure. It’s greatest benefit is reducing the cost of that infrastructure for companies by maximizing the usage of the physical resources.

Cloud Computing: Measured Resources, Pay for What You Use

Cloud Computing

While virtualization may be used to provide cloud computing, cloud computing is quite different from virtualization. Cloud computing may look like virtualization because it appears that your application is running on a virtual server detached from any reliance or connection to a single physical host. And they are similar in that fashion. However, cloud computing can be better described as a service where virtualization is part of a physical infrastructure.

Cloud computing grew out of the concept of utility computing. Essentially, utility computing was the belief that computing resources and hardware would become a commodity to the point that companies would purchase computing resources from a central pool and pay only for the amount of CPU cycles, RAM, storage and bandwidth that they used. These resources would be metered to allow a pay for what you use model much like you buy electricity from the electric company. This is how it became known as utility computing.

It is common for cloud computing to be distributed across many dedicated servers. This provides redundancy, high availability and even geographic redundancy. This also makes cloud computing very flexible. It is easy to add resources to your application. You just use them, just like you just use the electricity when you need it. Cloud computing has been designed with scalability in mind.

The biggest drawback of cloud computing is that, of course, you do not control the servers. Your data is out there in the cloud and you have to trust the provider that it is safe. Many cloud computing services offer SLAs that promise to deliver a level of service and safety but it is critical to read the fine print. A failure of the cloud service could result in a loss of your data.

Which One is Right for My Application?

How do you decide whether you need virtualization or cloud computing? They both can save money but they do it in different ways. One key consideration is when do you need to save the money. If you use virtualization, you will have a great deal of upfront cost. A new application will need servers and you’ll have to purchase the infrastructure for it. Virtualization means you’ll be spending less upfront and you will save money over time, but there is still going to be a large amount of capital spent early on. Cloud computing works in just the opposite fashion. You new application may not need many resources initially so cloud computing will likely cost very little in the beginning. However, as your application becomes popular and uses more resources, paying by the resource may become more expensive than using virtual servers on your own infrastructure.

Another important consideration is how safe will your data be. Are you comfortable with the cloud computing vendor? In a virtualized environment, you data is on your own hardware. You know who has access, where it is and how its being backed up. You also know exactly how you’ll handle a disaster recovery scenario. Cloud computing, on the other hand, places more that control in the hands of the vendor. While you’ll likely have a SLA to fall back on, it may not be enough. Last year, Microsoft had a failure in a data center that provided cloud computing services for T-Mobile’s Sidekick service. This failure resulted in the loss of customer data and a huge blow to T-Mobile’s reputation. While the SLA will likely provide some monetary compensation to T-Mobile, it cannot repair their reputation with the customers who lost data. You’ll want to consider carefully whether the SLA will cover all your bases as well.

Virtualization and cloud computing are both ways to reduce infrastructure cost by maximizing the utilization of computing resources. They are not the same thing however. Virtualization allows server consolidation by hosting many servers on a single piece of hardware where cloud computing is a service that delivers computer resources on a metered pay-as-you-go model. While they both have advantages, you’ll want to think about factors like start up cost versus long term costs and the possible loss of control of your infrastructure when deciding which model to utilize.

Sunday, 9 October 2011

Connection between PHP (server) and Android (client)

Nowadays, PHP and Android are widely used platforms, while PHP is used for dynamic web development, Android is an OS for mobiles, tablets etc. To develop Android applications we can use the benefits of PHP to communicate it with MySQL database and get required data from there.

We can use JSON and HTTP as an intermediate of communication between Android and PHP. The whole process can be divided into five steps:

1)      An HTTP request is sent from Android(Client) to PHP(Server).

2)      PHP runs it’s script to make connection with database, and send request to MySQL database for required data.

3)      MySQL responds back to PHP with requested data.

4)      PHP script analyse the date and coverts it into information. The whole information is then converted into JSON format and sent to the Android (Client).

5)      Android script reads the data, perform its operations and shows it on it’s screen.

The Whole process has also been described in the following diagram.


                                                      Figure : Android and PHP

 

Thanks!!!!!!!!!!! Enjoy Programming!!!!!!!! :)

 

 

Saturday, 8 October 2011

Overloading in PHP

PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments. In PHP it's achieved through magic methods.

Remember :
1) All overloading methods must be defined as public.
2) None of the arguments of these magic methods can be passed by reference.

In PHP we have following two types of overloading and their respective functions.

Property Overloading : Property overloading is achieved through __get(), __set(), __isset() and __unset() funtions.

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static.

<?php

require_once "DB.php";

class Persistable {
  
    private $data = array();
    private $table = "users";
  
    public function __construct($user) {
      
        $this->dbh  = DB::Connect("mysql://user:password@localhost/database");
        $query      = "SELECT id, name, email, country FROM " .$this->table . " WHERE name = ?";
        $this->data = $this->dbh->getRow($query, array($user),DB_FETCHMODE_ASSOC);
    }
  
    public function __get($member) {
      
        if (isset($this->data[$member])) {
            return $this->data[$member];
        }
    }
  
    public function __set($member, $value) {
      
        // The ID of the dataset is read-only
        if ($member == "id") {
            return;
        }
      
        if (isset($this->data[$member])) {
            $this->data[$member] = $value;
        }
    }
  
    public function __destruct() {
      
        $query = "UPDATE " . $this->table . " SET name = ?,email = ?, country = ? WHERE id = ?";
        $this->dbh->query($query, $this->name, $this->email,$this->country, $this->id);
    }
}

$class = new Persistable("Martin Jansen");
$class->name = "John Doe";
$class->country = "United States";
$class->email = "john@example.com";

?>


The code defines two special methods called __get() and __set(). __get() is called when reading the value of an undefined property, and __set() is called when changing the same property's value.

This means that whenever someone reads or writes an undefined property from the persistable class, the special methods manipulate the information in the $data property array instead of changing the class properties directly. (Remember: $data contains the row from the database!)

This is Property Overloading.


Methos Overloading : Method overloading is achieved through __call() and __callStatic() methods.

For Example :

<?php

    require_once "DB.php";

    class Persistable {
      
        private $data = array();
        private $table = "users";
        public function __construct($user) {
      
            $this->dbh = DB::Connect("mysql://user:password@localhost/database");
            $query = "SELECT id, name, email, country FROM " .$this->table . " WHERE name = ?";
            $this->data = $this->dbh->getRow($query, array($user),DB_FETCHMODE_ASSOC);
        }

        public function __get($member) {

            if (isset($this->data[$member])) {
                return $this->data[$member];
            }
        }
      
        public function __set($member, $value) {
      
            // The ID of the dataset is read-only
            if ($member == "id") {
                return;
            }
            if (isset($this->data[$member])) {
                $this->data[$member] = $value;
            }
        }
      
        public function __destruct() {
            $query = "UPDATE " . $this->table . " SET name = ?, email = ?, country = ? WHERE id = ?";
            $this->dbh->query($query, $this->name, $this->email, $this->country, $this->id);
        }
    }
  
    $class = new Persistable("Martin Jansen");
    $class->name = "John Doe";
    $class->country = "United States";
    $class->email = "john@example.com";
?>



Sunday, 2 October 2011

Explain ACID

The ACID model is one of the oldest and most important concepts of database theory. It sets forward four goals that every database management system must strive to achieve: atomicity, consistency, isolation and durability. No database that fails to meet any of these four goals can be considered reliable.

Let’s take a moment to examine each one of these characteristics in detail:


Atomicity :

states that database modifications must follow an “all or nothing” rule. Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. It is critical that the database management system maintain the atomic nature of transactions in spite of any DBMS, operating system or hardware failure.


Consistency :

states that only valid data will be written to the database. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. On the other hand, if a transaction successfully executes, it will take the database from one state that is consistent with the rules to another state that is also consistent with the rules.


Isolation :

requires that multiple transactions occurring at the same time not impact each other’s execution. For example, if Joe issues a transaction against a database at the same time that Mary issues a different transaction, both transactions should operate on the database in an isolated manner. The database should either perform Joe’s entire transaction before executing Mary’s or vice-versa. This prevents Joe’s transaction from reading intermediate data produced as a side effect of part of Mary’s transaction that will not eventually be committed to the database. Note that the isolation property does not ensure which transaction will execute first, merely that they will not interfere with each other.


Durability :

ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures.

Saturday, 1 October 2011

MySQL Basics


What Is MySQL :

MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server. It’s the most popular Open Source SQL database, provided by MySQL AB. MySQL AB is a commercial company that builds is business providing services around the MySQL database.

mysql vs mysqli       :        mysqli is the object-oriented version of mysql library functions.

Default Port             :        3306

Storage Engines      :        MyISAM, InnoDB, BDB(BerkeleyDB), MEMORY, CSV, BLACKHOLE  etc..


The following table describes the maximum length for each type of identifier.

Identifier
Maximum Length (characters)
Database Name
64
Table Name
64
Column Name
64
Index Name
64
Stored Function or Procedure
64
Trigger Name
64
View Name
64
Alias
255

Advantages of InnoDB over MyISAM?

Row-level locking, transactions, foreign key constraints and crash recovery.

Advantages of MyISAM over InnoDB?

Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.

Index

A data structure used for fast access to rows in a table. An index is usually built for the primary key of each table and can then be used to quickly find a particular row. Indexes are also defined and built for other attributes when those attributes are frequently used in queries

Notes:   

1) If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1,col2,col3), you have indexed search capabilities on (col1), (col1,col2), and (col1,col2,col3).

MySQL can't use a partial index if the columns don't form a leftmost prefix of the index. Suppose you have the SELECT statements shown below:

mysql> SELECT * FROM tbl_name WHERE col1=val1;
mysql> SELECT * FROM tbl_name WHERE col2=val2;
mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

If an index exists on (col1,col2,col3), only the first query shown above uses the index. The second and third queries do involve indexed columns, but (col2) and (col2,col3) are not leftmost prefixes of (col1,col2,col3).

2) Up to 32 indexes per table are allowed. Each index may consist of 1 to 16 columns or parts of columns. The maximum index length is 500 bytes (this may be changed when compiling MySQL). An index may use a prefix of a CHAR or VARCHAR field. Fixed-length and variable-length records.

Normalized database

A correctly designed database that is created from an ER model. There are different types or levels of normalization, and a third-normal form database is generally regarded as being an acceptably designed relational database.

Stored Procedures and Triggers

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep reissuing the entire query but can refer to the stored procedure. This provides better performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server.

A trigger is a stored procedure that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that automatically deletes the corresponding customer from a customer table when all his transactions are deleted.

The planned update language will be able to handle stored procedures, but without triggers. Triggers usually slow down everything, even queries for which they are not needed.
 
Table Locking in MySQL?
 
You can find a discussion about different locking methods in the appendix.

All locking in MySQL is deadlock-free. This is managed by always requesting all needed locks at once at the beginning of a query and always locking the tables in the same order.

1) The locking method MySQL uses for WRITE locks works as follows:

If there are no locks on the table, put a write lock on it. Otherwise, put the lock request in the write lock queue.

2) The locking method MySQL uses for READ locks works as follows:

If there are no write locks on the table, put a read lock on it. Otherwise, put the lock request in the read lock queue. When a lock is released, the lock is made available to the threads in the write lock queue, then to the threads in the read lock queue.

This means that if you have many updates on a table, SELECT statements will wait until there are no more updates.




Odoo 10: Close wizard and open standard form

Hi, Today we are going to learn how to open standard form after saving data in wizard. Let's say I have created an wizard to fill bas...