Saturday, November 29, 2008

Earn money online through niche sites?


 

It is not as easy as people say to earn an income using the potential of the Internet, but choosing the right tools and way makes it a lot easier. Many people give up on their dream after miserably struggling for months without any success at all. Niche marketing is one of these and also a very lucrative way to earn substantial amounts of money. Creating a niche website complete with RSS product feeds has created many wealthy Internet Marketers.

 

It is important that you promote your nice website according to the market you are targeting. The placing and promotion of your website will be most effective if the niche market is covered. You need to be very clear about the segment of the market you are targeting for. Then only start Promoting your website according to your target market.

 

First of all you will have to make your site search engine friendly so that search engine could rank your site easily and ultimately you get traffic. You need to place the ads and the links at the right places.

 

So the main thing is promotion of your website as this will decide the future of your online business and making money. If the promotional efforts done in this way make the niche market you are targeting aware of your existence, you have succeeded in your promotional efforts.

 

In order to make thousands of dollars a month you will need to create as many adsense niche sites as you can. Niche sites are great because they are highly targeted and convert well. The downside however, is that they do not receive as much traffic as a website that is built around a broader theme. A good adsense niche site will typical bring in a few hundred dollars a month. Solution is to buy 10 or 20 sites and you can begin to see the earning potential. You could also create 10 niche sites with the help of automated softwares also.

 

If you take these steps carefully you will promote your website successfully.

Find SEO Company for internet Marketing UK USA Canada Australia

Finding companies to profit from internet Marketing ?

We invest in companies where we are sure the share price does not reflect the real value of the business and where we have identified the reasons that will result in the share price going up. This has been our philosophy since  we  formation and our performance history fully vindicates this approach. Our highly successful investment approach has been fashioned over many years, combining real investment flair with a highly numerate decision making process. This means we offer our investors both the art and the science of fund management to generate for them superior investment returns.?

http://www.internetconsultantonline.com

Friday, November 28, 2008

How to Start a Profitable Home-Based Business Financing Your New Business

Financing Your New Business

If it is at all possible, you should start your business without any funding beyond your own. Do this by starting slowly and in conjunction with present employment. Start your business by working evenings and weekends while keeping your present job as long as practicable. This way, if the business does not meet your expectations, you have not incurred debt and will still have a job! However, in many instances outside funding will be required depending on the nature of the business. For example, expensive equipment or initial stock may be required. When determining your financing needs, remember that ..

I enjoy telling people that I "work at home." I can see that wistful look in their eyes, and I can hear it in their voices when they say, "That must be nice." And then for about five minutes, they do a little daydreaming about what it would be like to "work at home." I never explain to them about the measure of self-discipline it takes, and how great are the temptations to take a "break" and reorganize my sock drawer when I find myself faced with working on a project that is less than...

I have spent the last five years trying to work at home and have had some success. The following are a few facts I have to share with people who are either trying to or have given up trying to work at home. Q. What about places that put up "pay money to get a job" postings? Are they worth the money? Will I get a job if I spend the money? A. If a job asks for money, then it is not really a job. Think of it this way, would you pay to fill out an application for a job outside the home? No, of course you would not, so why you would pay someone for a work-at-home job? Let's say that ...

The most frequently asked question I receive as an Internet home business consultant usually goes something like this; "I would really like to start my own home business on the Internet, but I don't know what." The short answer is - Start with what you know and enjoy.There are a number of good reasons for this. By drawing on existing knowledge, you can concentrate on building a business rather than ...

In these days, it's becoming increasingly difficult to make ends meet with just one source of income. Thus, more and more people are investigating the possibilities of starting their own extra-income business. Most of these part-time endeavors are started and operated from the comfort and privacy of the home. Most of these people are making the extra money they need. Some have wisely and carefully built these extra income efforts into full-time, very profitable businesses. Others are ...

WORK AT HOME BUSINESS OPPORTUNITY!

Earn money online We will make you learn to earn online.

Work at Home and Earn Money Online

#1 WORK AT HOME BUSINESS OPPORTUNITY!
"TOP RATED" WORK AT HOME INTERNET BUSINESS FOR 2 YEARS AND RUNNING!
Largest Legitimate Home Business Opportunity on the Internet.


Work at home and earn money online!! Thousands of options are available and new business opportunities surface every day. How do you decide which one is right for you? Don't be pulled into the "get rich quick" promises...There are only a few legitimate work at home Internet businesses that result in online success and SIX FIGURE INCOME -  is #1 for second year in a row
!
http://outsourceteam.blogspot.com/

http://sourceoutsource.blogspot.com/2008/11/earn-work-at-home-earn-money-work-from.html



Earn Money Online | Without any investments | The Revolution Of Earning Money Online

Are you unemployed?
Are you disabled?
Are you a college student?
Need to make some extra cash?
Struggling with the tough economy?
Frustrated with all the money making scams on the web?
Do you just want to spend more time with your family?
Want to start living the life you've always dreamed of?


Read It Now!!

Hard work and determination will make your home based business a success and provide you with a steady stream of income. Starting a home based business is one of the most exciting and challenging endeavors you will ever undertake.

The thing is that when most people do find genuine work from home jobs, they don't advertise it so they can take advantage of the opportunity it presents. There are many companies that will gladly pay you to work from home because this frees up capital for them. They do offer legit work at home jobs because they do not have to purchase equipment and they only pay for the work that gets done.

A sound business plan and the will to succeed will set you apart from the competition. Choose the products or services you provide carefully. Make certain your services will be needed over the long term and make customer service your top priority. A loyal customer base is the key to the success or failure of your home-based business. A home based business is an excellent way to gain independence and financial freedom. A sound business plan and a strong work ethic are all it takes to succeed.

http://outsourceteam.blogspot.com/

Earn Work at Home | Earn Money | Work From Home | Earn Money at Home

Work at Home | Earn Money | Work From Home | Earn Money at Home

Today & Earn Easy Money Right Now. Just Dont Miss This Chance


Every Day!

Data Entry Workers Needed Immediately!

Work from Anywhere in the World - Start Today!


    1. Set your own hours.

    2. Work from your own home.

    3. Work whenever & wherever you want.

    4. Set your own income level.

    5. Be your own boss.






Work at Home - $250+/Day Jobs At Home? Make Money - Teach Online Home Business Online Data Entry from Home Work From Home

Our TOP members earn $250 - $1,400+ every day!   We have over 75,000 members in over 200 different countries.  You can join and work from anywhere in the world.

All that you need is a computer and access the the Internet. You do not need any special hardware or software to enter data online.

The enrollment process is fast & simple and you will receive your login information within minutes.

They  provides its' members with 24x7x365 access to the Members Area and unlimited customer service support.  There is a one-time enrollment fee of $49.50 and absolutely no other fees.

SEO Internet Online Marketing Experts London

 Internet Marketing Experts


Search engine optimization services from proven SEO company and search engine marketing company in India.

http://www.internetconsultantonline.com


From big corporate to small scale industries, it is imperative to have high ranking website listing in search engine. Topranker.in provides complete search engine placement services. We are a leading SEO company in India. We have complete website marketing and positioning solution for you. We also specialize in making search engine friendly websites.

Professional search engine optimization services in India. Topranker.in is search engine specialist offering SEO Services of web site to build up your corporate identity, increasing your product presence across the world and make to stay ahead of your competition. If you are looking for leadership status or maintaining your leadership status your search for web optimization company ends here. High search engine ranking or high search engine positioning can be achieved by strategic web site promotion. Topranker.in is an international SEO firm to share the power of information and advantage of knowledge by offer right web site promotion strategy to give you optimization ROI (return on investment) for internet marketing.


http://www.internetconsultantonline.com


There is a big difference between optimizing website and inserting meta tags than submitting website in major search engine and directories. It is an important internet marketing technology to make a perfect optimized website. Topranker.in is an undisputed leader in making cost-effective strategic web design, search engine optimization, search engine submissions, and search engine placement.

Web Design Search Engine Optimization company contact London UK

• Search Engine Optimization

• Online Reputation Management

• Internet Marketing

• Website Design

• Website Hosting

• Article And Blog Submission Service

• Search Engine Registration Service

• Website Analysis and Evaluation

• Logo and Graphic Design

•Corporate Branding

• Google Adwords Management 

for a no obligation quotation, to discuss what is possible for your site or for any further information please,

Contact us  http://www.internetconsultantonline.com

email    info@internetconsultantonline.com

SEO Search Engine Optimization

Our Online Reputation Management services offer real solutions to negative press that may exist regarding your product or service.

http://www.internetconsultantonline.com



Our Website Hosting packages offer affordable, reliable server solutions that can be dependence upon.
Search Engine Optimisation Services

So many times Web Site Design is used by designers to create clever and stunning visual sites only for no one to see them because they are invisible to search engines. Google runs one of the worlds largest popularity contests that rewards good Web Site Design & punishes mistakes severely.
Search Engine Marketing

Search engines score Web Site Design on a vast range of criteria, which are constantly assessed to ensure that the most suitable sites appear in your search results.


http://www.internetconsultantonline.com


Although Google tries to think like a human being, it is still only a computer & so relies upon a complex algorithm to compile the necessary data.This algorithm rely's upon looking for over one hundred different factors on each page which it then scores in order to be able to rank each site. These factors can also be over done so it is very important to seek professional guidance before attempting to optimize a site yourself.
Search engine Optimization,search engine marketing, seo graph 1

Google uses electronic "spiders" to search for links on web sites, & then follows them reading all the text it can find on the way. It likes to find keywords in groups, headings, image labels etc, but not too many otherwise it will think that you are trying too hard & will then begin to count them against you.

Google has a huge problem with reading images & Java Script (flash buttons/links etc). The problem is it can't read them or follow them. This means that whilst you may have the richest content on the web for you given topic, if your navigation devices are images or Java Script then all google will see is a blank page with no links & you will forever wallow at number 1,458,000 in the rankings.
Search Engine Optimization, search engine marketing,
Search Engine Optimization (seo)


http://www.internetconsultantonline.com


Deeho Search Engine Marketing (SEM) use tried & tested processes to make your web site Google friendly. We will Optimize every page of your site & in addition customize your web site from a Search Engine Optimization view point for your industry, adding pages that will significantly increase the quantity & quality of traffic flow into your site.
Search Engine Optimization, search engine marketing,


http://www.internetconsultantonline.com



All the major search engines use two types of scoring to evaluate web site Design, on page & off page. On page is as I have said above just a matter of making sure that your pages are in a format that Google likes to see & values highly. Off page Web Site Design is the second method of valuation for your site, namely "Is your site good enough so that other sites link to it?" Google looks at each & everyone of those links & the "Page Rank" of the site that the link is on & forms an opinion on that basis as to how popular your site is likely to be. If you for example have a link from a High Street Banks site that has a PR of 7/10 it will be worth far more than 100 links from your friends blog pages PR0/10.

There are so many factors to consider when getting involved in the Search Engine Optimization (optimisation)(seo) process that it can be too easy to miss a step along the way. We have the experience & Knowledge within the Internet Marketing arena to drive your web site to the top of the rankings.

This is not an overnight process however, from first contact to a top ten ranking can take up to a year as building a positive image for your site is a cumulative ongoing process that cannot be rushed.You should treat anyone who claims quick results with caution as it is not possible within the strict parameters set by Google. Only by combining all of the above mentioned factors can you build your Page Rank within Google & thus feature well.



http://www.internetconsultantonline.com


Search Engine Optimization(SEO) Services USA UK Canada Australia India

Search Engine Optimization(SEO) Services

http://www.internetconsultantonline.com

Search engine optimization or SEO is the art of placing your website in the first few pages of a search engine for a strategically defined set of keywords. In simple words it means that your website will appear on the first page of a search engine like Google, when someone searches for your product or service.

Why Search Engine Optimization?
# Major search engines command over 400 million searches everyday, day after day. A well designed Search engine optimization(SEO) program helps you get this piece of the pie, which you might be losing otherwise to your competition.
# SEO offers a much better return on investment than other traditional forms of internet marketing like banner campaigns and email marketing.
# Search Engine Optimization helps you capture targeted traffic... people who are already looking for the product or service you offer.
# Search Engine Optimization is a long term and permanent answer to your traffic woes. Once a website has been optimized for search engines it can stay at the top for long periods of time.

Learn more about Search Engine Optimization


Web Analytics & Website Usability

http://www.internetconsultantonline.com


You've got a great website and an awesome Search Marketing Campaign that results in tons of traffic to your site. But... Are you getting the most from this traffic, viz - Are the people coming to your site doing what you want them to do... Or are they just visiting the site and leaving?

Our Web Analytics & Website Usability Consultancy service helps you get the answer!

# More about Web Analytics
# More about Website Usability

       
Pay Per Click Campaign Management

Google Adwords Qualified Company Pay per click (PPC) advertising, also referred to as paid search marketing, is a form of online advertising in which you, the advertiser, pays the search engines, like Google or Yahoo, for every visitor that you get. The cost per click(CPC) that you incur can get expensive over time...

This is where we come in! Our PPC campaign managers continually monitor your bids, advertisements, competition and tweak your PPC campaign settings so that you get the most sales at the least cost.

Learn more about Pay Per Click Advertising

Social Media Marketing

http://www.internetconsultantonline.com


Web 2.0 has ushered in a new era in the still nascent world of internet marketing. Studies show that the advent of blogs, social media platforms, social bookmarking sites and other web 2.0 initiatives has resulted in over 44% of internet users becoming content creators. This combined with the increasing reach of search engines has resulted in an increase in exposure to any content that is created online.

Our Social Media Optimization services include blog marketing, reputation management and online branding. Find out more about our social media optimization services or contact us for a free consulting appointment.

Learn more about Social Media Marketing
Affiliate Marketing


You understand the importance of Search Engine Marketing, but want to move beyond simple Adwords-based advertising. You care about paying for results, not clicks. You want to reach specific audiences, build a focused advertiser network, display rich data, and preserve your brand.

If you want any of these, it's time for you to consider and evaluate an Affiliate Marketing Program.

Learn more about Affiliate Marketing

http://www.internetconsultantonline.com

Thursday, May 17, 2007

PHP Tricks help

Choose meaningful variable names and remember they're case-sensitive.
Use comments to remind you what your script does.
Remember that numbers don't require quotes, but strings (text) do.
You can use single or double quotes, but the outer pair must match.
Use a backslash to escape quotes of the same type inside a string.
To store related items together, use an array.
Use conditional statements, such as if and if... else, for decision making.
Simplify repetitive tasks with loops.
Use functions to perform preset tasks.
Display PHP output with echo or print.
Inspect the content of arrays with print_r().
With most error messages, work backward from the position indicated.
Keep smiling—and remember that PHP is not difficult.

Tuesday, May 15, 2007

THE H1B VISA PROCESS : USA UK CANADA Australia Jobs Search Engine

THE H1B VISA PROCESS :-
to obtain an H1B visa, an applicant must 'first' find an H1B job with an H1B visa employer company in the USA; commonly known as your 'H1B sponsor'.

Your H1B sponsor then applies for / files your H1B visa application. Individuals can NOT sponsor or apply for their own H1B visa - ONLY your new employer (sponsor) can.

An H1B visa is typically valid for up to six (6) years and entitles your spouse (husband/wife) and children to accompany you and 'live' in America.

One of the main advantages of the H1B visa (US work permit) is that it is a 'dual intent' visa which means that you can apply for a Green Card (Legal Permanent Residency).

To obtain an H1B visa to work in the USA....
* the 1st step is that you Must find an H1B Job with an H1B sponsor company.

* Individuals can Not sponsor/apply for your own H1B visa - only your new employer can.

H1B Visa Global Jobs Consultant Search Global jobs online UK USA CANADA and Australia

H-1B visa

http://globaljobsonline.blogspot.com

The US H1B visa is a non-immigrant visa, which allows a US company to employ a foreign individual for up to six years. As applying for a non-immigration visa is generally quicker than applying for a US Green Card, staff required on long-term assignment in the US are often initially brought in using a non-immigrant visa such as the H1B visa.

Individuals can not apply for an H1B visa to allow them to work in the US. The employer must petition for entry of the employee. H1B visas are subject to annual numerical limits.

US employers may begin applying for the H-1B visa six months before the actual start date of the visa. Since the beginning of the FY 2007 is October 1, 2006, employers can apply as soon as April 1, 2006 for the FY 2007 cap, but the beneficiary cannot start work until October 1st.

The H1B visa is designed to be used for staff in "speciality occupations", that is those occupations which require a high degree of specialized knowledge. Generally at least the equivalent of a job-relevant 4-year US Bachelor's degree is required (this requirement can usually be met by having a 3-year degree and 3 years' relevant post-graduate experience). However, professionals such as lawyers, doctors, accountants and others must be licensed to practice in the state of intended employment – e.g. a lawyer must generally have passed the relevant state bar exam.

Non-graduates may be employed on an H1B visa where they can claim to be 'graduate equivalent' by virtue of twelve or more years' experience in the occupation.

Positions that are not "speciality occupations", or for which the candidate lacks the qualifications/experience for an H1B visa, may be filled using an H-2B visa. The disadvantage of the H-2B visa is that it requires 'labor certification' - an expensive and time consuming process that involves extensive advertising of the position, and satisfying the authorities that there are no US workers available to do the job. Also, H-2B visas are initially granted only for one year, extendable in one year increments to a maximum of 3 years. As each extension requires a new Labor Certification, it unsurprising that, of the annual quota of 66,000 H-2B visas, only a few thousand are ever issued.

New H1B legislation requires certain employers, called 'H1B dependent employers' to advertise positions in the USA before petitioning to employ H1B workers for those positions. H1B dependent employers are defined as those having more than 15% of their employees in H1B status (for firms with over 50 employees – small firms are allowed a higher percentage of H1B employees before becoming 'dependent'). In addition all new H1B petitions and 1st extensions of H1B's now require a fee (in addition to the usual filing fees) of US$1,000 to be paid, which will be used to fund a training programme for resident US workers.

The initial visa may be granted for up to three years. It may then be extended, in the first instance for up to two further years, and eventually for one further year, to a maximum of six years. Those wishing to remain in the US for more than six years may, while still in the US on an H1B visa, apply for permanent residence (the "green card"): if such employees do not gain permanent residence, when the six year period runs out, they must live outside the US for at least one year before an application is made for them to enter on an H or an L visa.

Once a company has brought an employee to the US on an H1B visa, should the company dismiss that employee before the expiry of the visa, the company is liable for any reasonable costs that the employee incurs in moving him/herself, his/her effects, back to his/her last foreign residence. This provision covers only dismissal, it is not relevant when an employee chooses to resign.

Monday, May 14, 2007

Polymorphism PHP Mysql

Polymorphism

The database wrappers developed in this chapter are pretty generic. In fact, if you look at the other database extensions built in to PHP, you see the same basic functionality over and over againconnecting to a database, preparing queries, executing queries, and fetching back the results. If you wanted to, you could write a similar DB_Pgsql or DB_Oracle class that wraps the PostgreSQL or Oracle libraries, and you would have basically the same methods in it.

In fact, although having basically the same methods does not buy you anything, having identically named methods to perform the same sorts of tasks is important. It allows for polymorphism, which is the ability to transparently replace one object with another if their access APIs are the same.

In practical terms, polymorphism means that you can write functions like this:

function show_entry($entry_id, $dbh)
{
$query = "SELECT * FROM Entries WHERE entry_id = :1";
$stmt = $dbh->prepare($query)->execute($entry_id);
$entry = $stmt->fetch_row();
// display entry
}

This function not only works if $dbh is a DB_Mysql object, but it works fine as long as $dbh implements a prepare() method and that method returns an object that implements the execute() and fetch_assoc() methods.

To avoid passing a database object into every function called, you can use the concept of delegation. Delegation is an OO pattern whereby an object has as an attribute another object that it uses to perform certain tasks.

The database wrapper libraries are a perfect example of a class that is often delegated to. In a common application, many classes need to perform database operations. The classes have two options:

  • You can implement all their database calls natively. This is silly. It makes all the work you've done in putting together a database wrapper pointless.

  • You can use the database wrapper API but instantiate objects on-the-fly. Here is an example that uses this option:

    class Weblog {
    public function show_entry($entry_id)
    {
    $query = "SELECT * FROM Entries WHERE entry_id = :1";
    $dbh = new Mysql_Weblog();
    $stmt = $dbh->prepare($query)->execute($entry_id);
    $entry = $stmt->fetch_row();
    // display entry
    }
    }

    On the surface, instantiating database connection objects on-the-fly seems like a fine idea; you are using the wrapper library, so all is good. The problem is that if you need to switch the database this class uses, you need to go through and change every function in which a connection is made.

  • You implement delegation by having Weblog contain a database wrapper object as an attribute of the class. When an instance of the class is instantiated, it creates a database wrapper object that it will use for all input/output (I/O). Here is a re-implementation of Weblog that uses this technique:

    class Weblog {
    protected $dbh;
    public function setDB($dbh)
    {
    $this->dbh = $dbh;
    }
    public function show_entry($entry_id)
    {
    $query = "SELECT * FROM Entries WHERE entry_id = :1";
    $stmt = $this->dbh->prepare($query)->execute($entry_id);
    $entry = $stmt->fetch_row();
    // display entry
    }
    }

Now you can set the database for your object, as follows:

$blog = new Weblog;
$dbh = new Mysql_Weblog;
$blog->setDB($dbh);

Of course, you can also opt to use a Template pattern instead to set your database delegate:

class Weblog_Std extends Weblog {
protected $dbh;
public function _ _construct()
{
$this->dbh = new Mysql_Weblog;
}
}
$blog = new Weblog_Std;

Delegation is useful any time you need to perform a complex service or a service that is likely to vary inside a class. Another place that delegation is commonly used is in classes that need to generate output. If the output might be rendered in a number of possible ways (for example, HTML, RSS [which stands for Rich Site Summary or Really Simple Syndication, depending on who you ask], or plain text), it might make sense to register a delegate capable of generating the output that you want.

The Template Pattern - PHP Mysql Class

The Template Pattern

The Template pattern describes a class that modifies the logic of a subclass to make it complete.

You can use the Template pattern to hide all the database-specific connection parameters in the previous classes from yourself. To use the class from the preceding section, you need to constantly specify the connection parameters:

<?php
require_once 'DB.inc';

define('DB_MYSQL_PROD_USER', 'test');
define('DB_MYSQL_PROD_PASS', 'test');
define('DB_MYSQL_PROD_DBHOST', 'localhost');
define('DB_MYSQL_PROD_DBNAME', 'test');

$dbh = new DB::Mysql(DB_MYSQL_PROD_USER, DB_MYSQL_PROD_PASS,
DB_MYSQL_PROD_DBHOST, DB_MYSQL_PROD_DBNAME);
$stmt = $dbh->execute("SELECT now()");
print_r($stmt->fetch_row());
?>

To avoid having to constantly specify your connection parameters, you can subclass DB_Mysql and hard-code the connection parameters for the test database:

class DB_Mysql_Test extends DB_Mysql {
protected $user = "testuser";
protected $pass = "testpass";
protected $dbhost = "localhost";
protected $dbname = "test";

public function _ _construct() { }
}

Similarly, you can do the same thing for the production instance:

class DB_Mysql_Prod extends DB_Mysql {
protected $user = "produser";
protected $pass = "prodpass";
protected $dbhost = "prod.db.example.com ";
protected $dbname = "prod";

public function _ _construct() { }
}

Mysql Query Class - PHP OOP Method

Versions of MySQL prior to 4.1 do not provide a separate interface for users to prepare queries prior to execution or allow bind SQL. For us, though, passing all the variable data into the process separately provides a convenient place to intercept the variables and escape them before they are inserted into the query. An interface to the new MySQL 4.1 functionality is provided through Georg Richter's mysqli extension.

To accomplish this, you need to modify DB_Mysql to include a prepare method and DB_MysqlStatement to include bind and execute methods:

class DB_Mysql {
/* ... */
public function prepare($query) {
if(!$this->dbh) {
$this->connect();
}
return new DB_MysqlStatement($this->dbh, $query);
}
}
class DB_MysqlStatement {
public $result;
public $binds;
public $query;
public $dbh;
/* ... */
public function execute() {
$binds = func_get_args();
foreach($binds as $index => $name) {
$this->binds[$index + 1] = $name;
}
$cnt = count($binds);
$query = $this->query;
foreach ($this->binds as $ph => $pv) {
$query = str_replace(":$ph", "'".mysql_escape_string($pv)."'", $query);
}
$this->result = mysql_query($query, $this->dbh);
if(!$this->result) {
throw new MysqlException;
}
return $this;
}
/* ... */
}

In this case, prepare() actually does almost nothing; it simply instantiates a new DB_MysqlStatement object with the query specified. The real work all happens in DB_MysqlStatement. If you have no bind parameters, you can just call this:

$dbh = new DB_Mysql("testuser", "testpass", "localhost", "testdb");
$stmt = $dbh->prepare("SELECT *
FROM users
WHERE name = '".mysql_escape_string($name)."'");
$stmt->execute();

The real benefit of using this wrapper class rather than using the native procedural calls comes when you want to bind parameters into your query. To do this, you can embed placeholders in your query, starting with :, which you can bind into at execution time:

$dbh = new DB_Mysql("testuser", "testpass",
"localhost", "testdb");
$stmt = $dbh->prepare("SELECT * FROM users WHERE name = :1");
$stmt->execute($name);

The :1 in the query says that this is the location of the first bind variable. When you call the execute() method of $stmt, execute() parses its argument, assigns its first passed argument ($name) to be the first bind variable's value, escapes and quotes it, and then substitutes it for the first bind placeholder :1 in the query.

Even though this bind interface doesn't have the traditional performance benefits of a bind interface, it provides a convenient way to automatically escape all input to a query.

PHP Mysql Class

The Adaptor Pattern

The Adaptor pattern is used to provide access to an object via a specific interface. In a purely OO language, the Adaptor pattern specifically addresses providing an alternative API to an object; but in PHP we most often see this pattern as providing an alternative interface to a set of procedural routines.

Providing the ability to interface with a class via a specific API can be helpful for two main reasons:

  • If multiple classes providing similar services implement the same API, you can switch between them at runtime. This is known as polymorphism. This is derived from Greek: Poly means "many," and morph means "form."

  • A predefined framework for acting on a set of objects may be difficult to change. When incorporating a third-party class that does not comply with the API used by the framework, it is often easiest to use an Adaptor to provide access via the expected API.

The most common use of adaptors in PHP is not for providing an alternative interface to one class via another (because there is a limited amount of commercial PHP code, and open code can have its interface changed directly). PHP has its roots in being a procedural language; therefore, most of the built-in PHP functions are procedural in nature. When functions need to be accessed sequentially (for example, when you're making a database query, you need to use mysql_pconnect(), mysql_select_db(), mysql_query(), and mysql_fetch()), a resource is commonly used to hold the connection data, and you pass that into all your functions. Wrapping this entire process in a class can help hide much of the repetitive work and error handling that need to be done.

The idea is to wrap an object interface around the two principal MySQL extension resources: the connection resource and the result resource. The goal is not to write a true abstraction but to simply provide enough wrapper code that you can access all the MySQL extension functions in an OO way and add a bit of additional convenience. Here is a first attempt at such a wrapper class:

class DB_Mysql {
protected $user;
protected $pass;
protected $dbhost;
protected $dbname;
protected $dbh; // Database connection handle

public function _ _construct($user, $pass, $dbhost, $dbname) {
$this->user = $user;
$this->pass = $pass;
$this->dbhost = $dbhost;
$this->dbname = $dbname;
}
protected function connect() {
$this->dbh = mysql_pconnect($this->dbhost, $this->user, $this->pass);
if(!is_resource($this->dbh)) {
throw new Exception;
}
if(!mysql_select_db($this->dbname, $this->dbh)) {
throw new Exception;
}
}
public function execute($query) {
if(!$this->dbh) {
$this->connect();
}
$ret = mysql_query($query, $this->dbh);
if(!$ret) {
throw new Exception;
}
else if(!is_resource($ret)) {
return TRUE;
} else {
$stmt = new DB_MysqlStatement($this->dbh, $query);
$stmt->result = $ret;
return $stmt;
}
}
}

To use this interface, you just create a new DB_Mysql object and instantiate it with the login credentials for the MySQL database you are logging in to (username, password, hostname, and database name):

$dbh = new DB_Mysql("testuser", "testpass", "localhost", "testdb");
$query = "SELECT * FROM users WHERE name = '".mysql_escape_string($name)."'";
$stmt = $dbh->execute($query);

This code returns a DB_MysqlStatement object, which is a wrapper you implement around the MySQL return value resource:

class DB_MysqlStatement {
protected $result;
public $query;
protected $dbh;
public function _ _construct($dbh, $query) {
$this->query = $query;
$this->dbh = $dbh;
if(!is_resource($dbh)) {
throw new Exception("Not a valid database connection");
}
}
public function fetch_row() {
if(!$this->result) {
throw new Exception("Query not executed");
}
return mysql_fetch_row($this->result);
}
public function fetch_assoc() {
return mysql_fetch_assoc($this->result);
}
public function fetchall_assoc() {
$retval = array();
while($row = $this->fetch_assoc()) {
$retval[] = $row;
}
return $retval;
}
}

To then extract rows from the query as you would by using mysql_fetch_assoc(), you can use this:

while($row = $stmt->fetch_assoc()) {
// process row
}

PHP - A Brief Introduction to Design Patterns PHP Certification Free Tutorials


You have likely heard of design patterns, but you might not know what they are. Design patterns are generalized solutions to classes of problems that software developers encounter frequently.

If you've programmed for a long time, you have most likely needed to adapt a library to be accessible via an alternative API. You're not alone. This is a common problem, and although there is not a general solution that solves all such problems, people have recognized this type of problem and its varying solutions as being recurrent. The fundamental idea of design patterns is that problems and their corresponding solutions tend to follow repeatable patterns.

Design patterns suffer greatly from being overhyped. For years I dismissed design patterns without real consideration. My problems were unique and complex, I thoughtthey would not fit a mold. This was really short-sighted of me.

Design patterns provide a vocabulary for identification and classification of problems. In Egyptian mythology, deities and other entities had secret names, and if you could discover those names, you could control the deities' and entities' power. Design problems are very similar in nature. If you can discern a problem's true nature and associate it with a known set of analogous (solved) problems, you are most of the way to solving it.

To claim that a single chapter on design patterns is in any way complete would be ridiculous. The following sections explore a few patterns, mainly as a vehicle for showcasing some of the advanced OO techniques available in PHP.

PHP Class Overview Learn PHP Easy - Tutorials Globaljobsonline.blogspot.com

Introduction to OO Programming

It is important to note that in procedural programming, the functions and the data are separated from one another. In OO programming, data and the functions to manipulate the data are tied together in objects. Objects contain both data (called attributes or properties) and functions to manipulate that data (called methods).

An object is defined by the class of which it is an instance. A class defines the attributes that an object has, as well as the methods it may employ. You create an object by instantiating a class. Instantiation creates a new object, initializes all its attributes, and calls its constructor, which is a function that performs any setup operations. A class constructor in PHP5 should be named __construct() so that the engine knows how to identify it. The following example creates a simple class named User, instantiates it, and calls its two methods:

<?php
class User {
public $name;
public $birthday;
public function __construct($name, $birthday)
{
$this->name = $name;
$this->birthday = $birthday;
}
public function hello()
{
return "Hello $this->name!\n";
}
public function goodbye()
{
return "Goodbye $this->name!\n";
}
public function age() {
$ts = strtotime($this->birthday);
if($ts === -1) {
return "Unknown";
}
else {
$diff = time() - $ts;
return floor($diff/(24*60*60*365)) ;
}
}
}
$user = new User('george', '10 Oct 1973');
print $user->hello();
print "You are ".$user->age()." years old.\n";
print $user->goodbye();
?>

Running this causes the following to appear:

Hello george!
You are 29 years old.
Goodbye george!

The constructor in this example is extremely basic; it only initializes two attributes, name and birthday. The methods are also simple. Notice that $this is automatically created inside the class methods, and it represents the User object. To access a property or method, you use the -> notation.

On the surface, an object doesn't seem too different from an associative array and a collection of functions that act on it. There are some important additional properties, though, as described in the following sections:

  • Inheritance Inheritance is the ability to derive new classes from existing ones and inherit or override their attributes and methods.

  • Encapsulation Encapsulation is the ability to hide data from users of the class.

  • Special Methods As shown earlier in this section, classes allow for constructors that can perform setup work (such as initializing attributes) whenever a new object is created. They have other event callbacks that are triggered on other common events as well: on copy, on destruction, and so on.

  • Polymorphism When two classes implement the same external methods, they should be able to be used interchangeably in functions. Because fully understanding polymorphism requires a larger knowledge base than you currently have, we'll put off discussion of it until later in this chapter, in the section "Polymorphism."

Inheritance

You use inheritance when you want to create a new class that has properties or behaviors similar to those of an existing class. To provide inheritance, PHP supports the ability for a class to extend an existing class. When you extend a class, the new class inherits all the properties and methods of the parent (with a couple exceptions, as described later in this chapter). You can both add new methods and properties and override the exiting ones. An inheritance relationship is defined with the word extends. Let's extend User to make a new class representing users with administrative privileges. We will augment the class by selecting the user's password from an NDBM file and providing a comparison function to compare the user's password with the password the user supplies:

class AdminUser extends User{
public $password;
public function _ _construct($name, $birthday)
{
parent::_ _construct($name, $birthday);
$db = dba_popen("/data/etc/auth.pw", "r", "ndbm");
$this->password = dba_fetch($db, $name);
dba_close($db);
}
public function authenticate($suppliedPassword)
{
if($this->password === $suppliedPassword) {
return true;
}
else {
return false;
}
}
}

Although it is quite short, AdminUser automatically inherits all the methods from User, so you can call hello(), goodbye(), and age(). Notice that you must manually call the constructor of the parent class as parent::_ _constructor(); PHP5 does not automatically call parent constructors. parent is as keyword that resolves to a class's parent class.

Encapsulation

Users coming from a procedural language or PHP4 might wonder what all the public stuff floating around is. Version 5 of PHP provides data-hiding capabilities with public, protected, and private data attributes and methods. These are commonly referred to as PPP (for public, protected, private) and carry the standard semantics:

  • Public A public variable or method can be accessed directly by any user of the class.

  • Protected A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

  • Private A private variable or method can only be accessed internally from the class in which it is defined. This means that a private variable or method cannot be called from a child that extends the class.

Encapsulation allows you to define a public interface that regulates the ways in which users can interact with a class. You can refactor, or alter, methods that aren't public, without worrying about breaking code that depends on the class. You can refactor private methods with impunity. The refactoring of protected methods requires more care, to avoid breaking the classes' subclasses.

Encapsulation is not necessary in PHP (if it is omitted, methods and properties are assumed to be public), but it should be used when possible. Even in a single-programmer environment, and especially in team environments, the temptation to avoid the public interface of an object and take a shortcut by using supposedly internal methods is very high. This quickly leads to unmaintainable code, though, because instead of a simple public interface having to be consistent, all the methods in a class are unable to be refactored for fear of causing a bug in a class that uses that method. Using PPP binds you to this agreement and ensures that only public methods are used by external code, regardless of the temptation to shortcut.

Static (or Class) Attributes and Methods

In addition, methods and properties in PHP can also be declared static. A static method is bound to a class, rather than an instance of the class (a.k.a., an object). Static methods are called using the syntax ClassName::method(). Inside static methods, $this is not available.

A static property is a class variable that is associated with the class, rather than with an instance of the class. This means that when it is changed, its change is reflected in all instances of the class. Static properties are declared with the static keyword and are accessed via the syntax ClassName::$property. The following example illustrates how static properties work:

class TestClass {
public static $counter;
}
$counter = TestClass::$counter;

If you need to access a static property inside a class, you can also use the magic keywords self and parent, which resolve to the current class and the parent of the current class, respectively. Using self and parent allows you to avoid having to explicitly reference the class by name. Here is a simple example that uses a static property to assign a unique integer ID to every instance of the class:

class TestClass {
public static $counter = 0;
public $id;

public function _ _construct()
{
$this->id = self::$counter++;
}
}

Special Methods

Classes in PHP reserve certain method names as special callbacks to handle certain events. You have already seen _ _construct(), which is automatically called when an object is instantiated. Five other special callbacks are used by classes: _ _get(), _ _set(), and _ _call() influence the way that class properties and methods are called, and they are covered later in this chapter. The other two are _ _destruct() and _ _clone().

_ _destruct() is the callback for object destruction. Destructors are useful for closing resources (such as file handles or database connections) that a class creates. In PHP, variables are reference counted. When a variable's reference count drops to 0, the variable is removed from the system by the garbage collector. If this variable is an object, its _ _destruct() method is called.

The following small wrapper of the PHP file utilities showcases destructors:

class IO {
public $fh = false;
public function _ _construct($filename, $flags)
{
$this->fh = fopen($filename, $flags);
}
public function _ _destruct()
{
if($this->fh) {
fclose($this->fh);
}
}
public function read($length)
{
if($this->fh) {
return fread($this->fh, $length);
}
}
/* ... */
}

In most cases, creating a destructor is not necessary because PHP cleans up resources at the end of a request. For long-running scripts or scripts that open a large number of files, aggressive resource cleanup is important.

In PHP4, objects are all passed by value. This meant that if you performed the following in PHP4:

$obj = new TestClass;
$copy = $obj;

you would actually create three copies of the class: one in the constructor, one during the assignment of the return value from the constructor to $copy, and one when you assign $obj to $copy. These semantics are completely different from the semantics in most other OO languages, so they have been abandoned in PHP5.

In PHP5, when you create an object, you are returned a handle to that object, which is similar in concept to a reference in C++. When you execute the preceding code under PHP5, you only create a single instance of the object; no copies are made.

To actually copy an object in PHP5, you need to use the built-in _ _clone() method. In the preceding example, to make $copy an actual copy of $obj (and not just another reference to a single object), you need to do this:

$obj = new TestClass;
$copy = $obj->_ _clone();

For some classes, the built-in deep-copy _ _clone() method may not be adequate for your needs, so PHP allows you to override it. Inside the _ _clone() method, you have $this, which is the new object with all the original object's properties already copied. For example, in the TestClass class defined previously in this chapter, if you use the default _ _clone() method, you will copy its id property. Instead, you should rewrite the class as follows:

class TestClass {
public static $counter = 0;
public $id;
public $other;

public function _ _construct()
{
$this->id = self::$counter++;
}
public function _ _clone()
{
$this->id = self::$counter++;
}
}

http://zendphp.blogspot.com/

http://zendexam.blogspot.com/

http://zendcertification.blogspot.com/