MySQL Database Handling in PHP

MySQL Database Handling in PHP

by: John L

Most interactive websites nowadays require data to be presented dynamically and interactively based on input from the user. For example, a customer may need to log into a retail website to check his purchasing history. In this instance, the website would have stored two types of data in order for the customer to perform the check – the customer’s personal login details; and the customer’s purchased items. This data can be stored in two types of storage – flat files or databases.

Flat files are only feasible in very low to low volume websites as flat files have 3 inherent weaknesses:

The inability to index the data. This makes it necessary to potentially read ALL the data sequentially. This is a major problem if there are a lot of records in the flat file because the time required to read the flat file is proportionate to the number of records in the flat file.

The inability to efficiently control access by users to the data

The inefficient storage of the data. In most cases, the data would not be encrypted or compressed as this would exacerbate the problem no. 1 above

The alternative which is, in my opinion, the only feasible method, is to store the data in a database. One of the most prevalent databases in use is MySQL. Data that is stored in a database can easily be indexed, managed and stored efficiently. Besides that, most databases also provide a suite of accompanying utilities that allow the database administrator to maintain the database – for example, backup and restore, etc.

Websites scripted using PHP are very well suited for the MySQL database as PHP has a custom and integrated MySQL module that communicates very efficiently with MySQL. PHP can also communicate with MySQL through the standard ODBC as MySQL is ODBCcompliant, However, this will not be as efficient as using the custom MySQL module for PHP.

The rest of this article is a tutorial on how to use PHP to:

Connect to a MySQL database

Execute standard SQL statements against the MySQL database

Starting a Session with MySQL

Before the PHP script can communicate with the database to query, insert or update the database, the PHP script will first need to connect to the MySQL server and specify which database in the MySQL server to operate on.

The mysql_connect() and mysql_select_db() functions are provided for this purpose. In order to connect to the MySQL server, the server name/address; a username; and a valid password is required. Once a connection is successful, the database needs to be specified.

The following 2 code excerpts illustrate how to perform the server connection and database selection:

@mysql_connect(ก[servername]ก, ก[username]ก, ก[password]ก) or die(กCannot connect to DB!ก);

@mysql_select_db(ก[databasename]ก) or die(กCannot select DB!ก);

The @ operator is used to suppress any error messages that mysql_connect() and mysql_select_db() functions may produce if an error occurred. The die() function is used to end the script execution and display a custom error message.

Executing SQL Statements against a MySQL database

Once the connection and database selection is successfully performed, the PHP script can now proceed to operate on the database using standard SQL statements. The mysql_query() function is used for executing standard SQL statements against the database. In the following example, the PHP script queries a table called tbl_login in the previously selected database to determine if a username/password pair provided by the user is valid.

Assumption:

The tbl_login table has 3 columns named login, password, last_logged_in. The last_logged_in column stores the time that the user last logged into the system.

// The $username and $passwd variable should rightly be set by the login form

// through the POST method. For the purpose of this example, we’re manually coding it.

$username = ขjohnข;

$passwd = ขmypasswordข;

// We generate a SELECT SQL statement for execution.

$sql=กSELECT * FROM tbl_login WHERE login = กก.$username.กก AND password = กก.$passwd.กกก;

// Execute the SQL statement against the currently selected database.

// The results will be stored in the $r variable.

$r = mysql_query($sql);

// After the mysql_query() command executes, the $r variable is examined to

// determine of the mysql_query() was successfully executed.

if(!$r) {

$err=mysql_error();

print $err;

exit();

}

// If everything went well, check if the query returned a result – i.e. if the username/password

// pair was found in the database. The mysql_affected_rows() function is used for this purpose.

// mysql_affected_rows() will return the number of rows in the database table that was affected

// by the last query

if(mysql_affected_rows()==0){

print กUsername/password pair is invalid. Please try again.ก;

}

else {

// If successful, read out the last logged in time into a $last variable for display to the user

$row=mysql_fetch_array($r);

$last=$row[กlast_logged_inก];

print ขLogin successful. You last logged in at ข.$last.ข.ข;

}

The above example demonstrated how a SELECT SQL statement is executed against the selected database. The same method is used to execute other SQL statements (e.g. UPDATE, INSERT, DELETE, etc.) against the database using the mysql_query() and mysql_affected_rows() functions.

About The Author

This PHP scripting article is written by John L. John L is the Webmaster of The Ultimate BMW Blog! (http://www.bimmercenter.com).

The Ultimate BMW Blog!

[email protected]

This article was posted on November 07, 2004

by John L

7 Tips for Testing Your Sales and Marketing

7 Tips for Testing Your Sales and Marketing

by: Angela Wu

One marketing technique may work wonders for someone, but that doesn’t guarantee that itกll do the same for you. The only way to really know what works for YOUR products and YOUR target audience is to experiment. Testing and experimentation are crucial to increasing your profits.
1. Try using the occasional popup window to get more subscribers to your newsletter. Some people *really* hate these, so use them sparingly. For example, you could have a window pop up only the first time someone visits your site … or you could have one appear whenever someone leaves your site. Try different scenarios to see what works best.
2. Change the price of your product and see what impact it has on sales. Even if your sales drop, you may still come out ahead when it comes to profits. Note: your sales may not drop at all; I increased the price of my own booklet from $12.95 to $19.95 and sales stayed the same. You never know until you try.
3. Test different sales copy on your website and in your autoresponder. Should you come on strong, be subtle, be extremely detailed? Does long sales copy do better than short copy, or vice versa? Do you get more sales by spreading your sales copy on multiple pages, or by putting it all on one page? Be sure to make backups of your previous work; if you find the new copy kills sales, you can always restore the previous version.
4. Track your advertising. There are a number of commercially available ad tracking packages that can help you see which ads are working well and which aren’t. Discard anything that doesn’t work, and try to improve on ads that appear to work well.
5. Experiment with the navigation of your website. For example, change the number of clicks required to get to your ordering page, or change the flow of navigation so that your visitor always ends up at an ordering page.
6. Test different types of links. You might try short ads in the margins of your web pages vs. text links within the context of an article, for example.
7. Test response rates between direct links to your sales page and the use of a followup autoresponder. Sometimes people just need an extra กpushก or a reminder to order. (make sure your autoresponder has an easy way for your prospect to unsubscribe)

About The Author

Angela runs several successful sites dedicated to helping beginners profit from the Internet. Her new web magazine, Online Business Basics, features stepbystep tutorials for eBusiness กnewbiesก. To take the guesswork out of starting and building an Internet business, click over to http://www.onlinebusinessbasics.com/

This article was posted on February 4, 2002

by Angela Wu

Making Your Purpose Your Business, Step#4

Making Your Purpose Your Business, Step#4

by: Heather J. Tait

Step#4 – Organizing & Developing Online Content

If you have done your homework then you are ready to organize and develop what will be your online content. Your content is very important as it will be used for promoting you, your work, and your website. Content serves a variety of purposes; it displays public relations, target marketing, and general information to build a platform for your product (your purpose).

One of the main items that need attention would be your biography. If you are an artist or writer, you will get asked for this pertinent information every time you make a submission or apply for competitions. Your biography is an essential piece of information that often can get viewed prior to your work. Even if your target audiences are publishers, agents, or clients, you have only one chance to intrigue them and make a good first impression.

There are several ways that you can address your audience. If you would like to be up front and personal, you can write in first person, using ขIข in your sentence structure. For example, ขI was born in Silver Springs, Maryland.ข If you want to have a general sound or professional structure, you can write in the third person, referring to yourself as stated in this example, ขHeather J. Tait was born in Silver Springs, Maryland.ข

It’s really up to you on how you would like to address your audience. I personally prefer writing in third person when referring to my work mainly because I feel it conveys a sense of professional etiquette. It creates a press release persona that can maintain your audience’s attention. However, if you prefer to write in first person you can do that and still have strength to your sentences. Either way you want to spark your audience’s interest in you and your work.

The difference between a how a hobbyist or a professional artist or writer can be determined simply on how they are conveyed through content. You want your sentences to have strength and power to them. Each word and phrase counts because they are performing a difficult task, representing you, when you are not there to do so. For example you could say, ขI’m an artist from Erie, PA. I am trying to make a living doing art. Hope you will look at my work.ข This sentence hardly provides any credibility to my name or my art. It conveys that I am not really serious about what I’m doing, but I still would like you to look at my work. That’s a lofty expectation to have of my audience when I lack taking myself serious.

A professional sentence structure as an example, ขHeather J. Tait was raised in Erie, PA and began her career as a professional artist in 1997.ข You want to state who you are, where you come from, and what it is you do. You want your opening sentence to really state a few basic facts about you and your work. This is not an easy task and perhaps one of the reasons why many artists and writers procrastinate completing a biography. Perhaps one of the reasons why, just as Alan Wilson Watts states, ขTrying to define yourself is like trying to bite your own teeth.ข

It’s quite the challenge to write about yourself and really expand on your talents. You have to convey your work and yourself from almost another person’s perspective. Imagine yourself as a Public Relations Specialist and you were just hired to write about an artist or writer. What are some things you would need to know about that person? What strong points do you want to enunciate about this person’s life and accomplishments? What active role does this person assume now?

You don’t have to be overly personal but you really want to give your audience a sense of who you are. Let them know how you began your career. Write about your technique or your style. It is possible to be personal but also professional. You may have to work on several drafts until you get a nice flow of words and a functional biography. The time you put into writing this valuable piece of information will pay off by getting people to take notice in something very dear to you, your purpose. So share your passion with your audience. You just may notice that your enthusiasm might be contagious.

You want to have a short version (100150 words) of your biography and then a long version (5001,000 words). It’s advisable to work on your long version first so then you can easily copy a short version by taking excerpts. As an example you can view my biography online: http://www.silencespeaks.com/artist/artist.html. I had a shorter version posted several months back, but because of numerous requests to know more about me, I had to rewrite it. You may experience similar feedback from your viewers. The long version will be for your website and the shorter version will be used for promotional websites that commonly limit your biography to 100150 words.

You can also write a statement about your work. A statement simply is a personal claim about your work or perhaps on what inspires your work. Get creative here and really just type what you feel you need to express about your creativity. I was asked for an artist statement back in 1999. I had no clue what that was but I wrote one down. I’ve used the same statement ever since. You can view it online to get an example: http://www.silencespeaks.com/artist/artist.html

Take time to really write down your talents and accomplishments and don’t be afraid to express them in your content. The more people learn about you, the more they will be able to relate to you.

Your challenge for this month is to create a full length and short version of your biography. As a bonus create an artistic statement if you would like. Read other artists’ or writers’ biographies and ask yourself which ones interested you and then explain why. Which biographies had strong statements, which ones were weak? Then take that information and apply it to yourself. Evaluate what traits you want to express, organize an outline, and then write your biography.

By Artist & Inspirational Writer Heather J.Tait

About The Author

Silence Speaks http://www.silencespeaks.com

read more articles from this author at Silence Speaks Inspirations

Artist and inspirational writer Heather J. Tait began her career as a professional artist back in 1997 in Morgan Hill, CA. Her style combines simplicity and complexity. She uses bold lines with the aid of her Sharpie Marker and completes the process with splashes of bright watercolors.

Her work can best be described in its entirety as inspirational. She has over 160 pieces of all original works with inspirational quotes that correspond to each piece.

Her art as well as articles are syndicated internationally. Her work has been featured in the Spire Press (New York, NY), the Gutenburg Litegraphic Society (Salt Lake City, UT), Tony Awards (Atlanta,GA) and the FOX Theater (Atlanta,GA) to name a few.

She was also recently inducted into the Who’s Who of American Women 20042005the definitive biographical resource featuring the most accomplished women in all areas of human endeavor.

She is also the founder of Silence Speaks International Artist Association and Intrigue Magazine which works to promote artists and writers.

[email protected]

This article was posted on September 13, 2004

by Heather J. Tait

USP Unique Selling Propositions

USP Unique Selling Propositions

by: Scott กGearsก

If you have competitors, then you should have at least one Unique Selling Proposition (USP). The more REAL ones you have, the better for your Branding, your business recognition, and your sales!

We all have competitors, and the more you have, the more important it is that you have a Unique Selling Proposition (at least one).

Allow me to explain. Letกs use a recent example of a company that sells laser toner cartridges… Do you think they have competition online? You bet they do, another category that is swamped with resellers. Sound like yours?

The task of coming up with a USP can sometimes be tough. But every company needs this, it sets you apart from your competitors. Let me stress this again, it is one or more reasons why prospects should work with you, or buy from you, or do business with you, instead of your competitors, period.

Let me narrow this a little further, it used to be if you had the best price, you got the business. Although still a minor USP, price alone should not be the only consideration, itกs not really that unique… Yes, you still need to be competitive, but I don’t want to be the cheapest guy… we’re in this to make a profit, right? So don’t make price your กonlyก USP. Combine it with more value, something your competition doesn’t do, or doesn’t offer.

O.K., back to our example. This company needed more than price, their product pricing is right inline with everyone else, so now what?

First of all, you need to know what your competitors do offer.

This is not a new concept. You can’t compete if you don’t know what you’re up against. So take a little time and check out what they have. Do some research, youกd be surprised what you might find or not. Special offers, free shipping, a contest, great customer support?

Take a step back, imagine you are the customer and you do buy toner from someone a few times a year. If they do not get great service or itกs just average, then chances are you can sway them your way. This references กcustomer loyaltyก another chapter, but it follows first getting the customer. So, letกs get the prospect as a customer first.

Now, what do we do to sway these prospects? We offer them what the competition doesn’t. This can be discovered with your competitive research. Oh, and if you still haven’t found a USP or a few then Hyperformance Media can help you with this as well.

Write down every idea that you and your team come up with. Please don’t worry about how silly they might seem (at the time), just brainstorm with the data you have gained. The reason I say to include the silly ones, and others is because sometimes those little ideas that you laughed at can actually be morphed to create your USP. No idea is too far fetched at this point, and usually the ideas you laughed at are, in fact, some things your competitors don’t offer. Thatกs where we go next.

On the toner company we came up with all kinds, some were already offered by competitors, some were not. The idea is to initially come up with as many as possible. Here are some of what we narrowed the field to (we started with about two dozen);

Price (of course)

Free Shipping (varied by quantity/price)

Great Customer Service (so everyone says)

A Contest / Promotion (a what?)

Free Gifts (vary)

Referral Savings (with parameters)

Reminders? (to buy)

The next step is again to nail down our list, get creative, really think here. This alone still makes us more competitive (once implemented), even if others use the same approach. Why? Because before we did this, there was a ton of competition, and as we add these USPกs we now narrow the list of our ‘realก competitors. We are now more competitive within our industry, because we now offer things that (most) of our competitors do not!

We are getting more competitive immediately by implementing some simple offerings. Letกs take each one in this example and see how we can use it or discard it to our advantage.

Price Still very important in any market, but very tied to customer value (or perceived value). If your product or service is not competing here it does not necessarily rule you out, more on this later. However, this is usually where a shopper starts (because itกs easy), and you want to be considered with this group. In this example, we agreed that (based on our research) we were in the market on price. So our price is competitive and thatกs great, but not unique enough to get the business.

Free Shipping In our research, we found that most of the companyกs who were offering this service were just a couple dollars higher in price (covering their กfreeก offer). So while it may have some perceived value, it was not enough for this company to offer that, so we discarded this one. If however, your costs are such that you can ship for free and still be competitive and profitable, this is a worthwhile USP.

Great Customer Service This is stated everywhere, making it tough for the consumer to know what is reality. It is hard to judge until you are a customer. It would be more valuable to offer testimonials of Great Customer Satisfaction. Not Customer Service, but Customer Satisfaction. There is a big difference here. So we DO want to take some of our really satisfied customers and put together, or request their testimonials. This is much more powerful than the words or promise of กGreat Customer Serviceก. So we will use this, but focusing on satisfaction with testimonials in our advertising pieces and website, etc.

A Contest/Promotion This covers a broad area, but can be extremely successful when implemented and marketed properly, so be creative and if possible, develop one for your business, product or service. After our discussions, and research, we have begun developing this idea. Example: Every time you buy from us, you get another chance at winning กFree Toner for a Yearก. I know you’re saying… free toner for a year what are you crazy? Bear with me on this… first of all, most of their customers use 4 to 6 toners in normal use in one year (In our contest, we can actually cap that in our rules, i.e., กNot to exceed 6 cartridgesก. So we associate our costs to that, which does not make this a cost prohibitive program at all, depending upon the program success. Again, the mileage and customers we gain from our contest is potentially huge, and if it works well, we continue it… at a maximum cost of 6 toners per year for a Grand Prize.

Free Gifts Don’t discount this one, many people grab hold of these กoffersก to feel like they are making out. All else being the same, the customer does get something for nothing. Now, if the item truly has no value, then the customer has little to no interest. And, it actually กcheapensก the image of your firm (be careful). We decided with our products and business customer profile, this would not work for this business. But it could work for you or your products.

Referral Programs Another potential attraction (savings) for your customer. I say potential because this type of referral program, like price, should not be the only USP. When used in conjunction with others, this can steadily grow your business (sales) as well. You need to develop a program that somehow rewards referrals. For example, it can be something simple like ‘refer a customer to our business and when we ship their order you will receive or accrue credits, dollars, points, or 5% off your next orderก. Get the idea? The key is to make it of value, and still keep it cost effective.

Reminders This was it! The big one, it was unique, it has great value to the customer, and it reinforces our Customer Satisfaction! This was also laughed at when first mentioned.

So? What was the plan? We acquire a software program that can be set to automatically email each customer based on their own usage when their toner and supplies were potentially running low (i.e., 30 or 90 days or any date we choose. Once setup it is all automated (cost effective)! It also gave us their email address (important anytime) and with our reminders we could include any special or seasonal offers that might further attract more sales.

So, what did this company find?

In a nutshell Their products are priced well to compete. In this case, we discarded free shipping as not really cost effective. We stressed Satisfied Customers in all of our marketing materials with testimonials and reallife examples. We are also developing a contest to further set us apart from our competitors. We could not find a free gift we thought would add any value to the customer (but continue to look). They are considering a Referral Program as well. The real USP in combination with the others was our unique Email Reminder System. At that time, no other competitor was offering anything like this! This IS a Unique Selling Proposition and was perfect for our example. Put all these together, and this company has numerous กedgesก on their competition. Once customers are aware of these differences that set you apart from all the rest growth is almost certain! That company is in a much better position to กownก their market online, or at a minimum increase their market share.

The more you get the word out, the more you’re sure to benefit from these type ideas.

I understand this was a pretty broad example but you should get the idea.

You won’t always come up with an idea that no competitor has or offers, but if only 36 competitors offer that same USP, you are still in the top tier of your competition instead of lost somewhere unnoticed while buyers continue to purchase through your competition. You decide.

Use this article for your training, website, or newsletter by simply adding the following footer;

Written by and Copyright © 2003

www.hyperformancemedia.com

About The Author

Scott is the Founder and Sr. Project Manager for Hyperformance Media.com, a Technology Marketing Company serving online businesses since 1996. His 23+ years of experience in the computer industry will help you succeed. Their website offers free education & resources that will assist any business in successfully marketing their company online.

[email protected]

This article was posted on March 03, 2003

by Scott กGearsก

Mastering Regular Expressions in PHP

Mastering Regular Expressions in PHP

by: Dennis Pallett

What are Regular Expressions?

A regular expression is a pattern that can match various text strings. Using regular expressions you can find (and replace) certain text patterns, for example กall the words that begin with the letter Aก or กfind only telephone numbersก. Regular expressions are often used in validation classes, because they are a really powerful tool to verify email addresses, telephone numbers, street addresses, zip codes, and more.

In this tutorial I will show you how regular expressions work in PHP, and give you a short introduction on writing your own regular expressions. I will also give you several example regular expressions that are often used.

Regular Expressions in PHP

Using regex (regular expressions) is really easy in PHP, and there are several functions that exist to do regex finding and replacing. Letกs start with a simple regex find.

Have a look at the documentation of the preg_match function (http://php.net/preg_match). As you can see from the documentation, preg_match is used to perform a regular expression. In this case no replacing is done, only a simple find. Copy the code below to give it a try.

<?php

// Example string

$str = "Letกs find the stuff <bla>in between</bla> these two previous brackets";

// Letกs perform the regex

$do = preg_match("/<bla>(.*)<\/bla>/", $str, $matches);

// Check if regex was successful

if ($do = true) {

// Matched something, show the matched string

echo htmlentities($matches[ก0ก]);

// Also how the text in between the tags

echo ก<br />ก . $matches[ก1ก];

} else {

// No Match

echo "Couldn’t find a match";

}

?>

After having run the code, itกs probably a good idea if I do a quick run through the code. Basically, the whole core of the above code is the line that contains the preg_match. The first argument is your regex pattern. This is probably the most important. Later on in this tutorial, I will explain some basic regular expressions, but if you really want to learn regular expression then itกs best if you look on Google for specific regular expression examples.

The second argument is the subject string. I assume that needs no explaining. Finally, the third argument can be optional, but if you want to get the matched text, or the text in between something, itกs a good idea to use it (just like I used it in the example).

The preg_match function stops after it has found the first match. If you want to find ALL matches in a string, you need to use the preg_match_all function (http://www.php.net/preg_match_all). That works pretty much the same, so there is no need to separately explain it.

Now that weกve had finding, letกs do a findandreplace, with the preg_replace function (http://www.php.net/preg_replace). The preg_replace function works pretty similar to the preg_match function, but instead there is another argument for the replacement string. Copy the code below, and run it.

<?php

// Example string

$str = "Letกs replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace

$result = preg_replace ("/<bla>(.*)<\/bla>/", "<bla>new stuff</bla>", $str);

echo htmlentities($result);

?>

The result would then be the same string, except it would now say กnew stuffก between the bla tags. This is of course just a simple example, and more advanced replacements can be done.

You can also use keys in the replacement string. Say you still want the text between the brackets, and just add something? You use the $1, $2, etc keys for those. For example:

<?php

// Example string

$str = "Letกs replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace

$result = preg_replace ("/<bla>(.*)<\/bla>/", "<bla>new stuff (the old: $1)</bla>", $str);

echo htmlentities($result);

?>

This would then print กLetกs replace the new stuff (the old: stuff between) the bla bracketsก. $2 is for the second กcatchallก, $3 for the third, etc.

Thatกs about it for regular expressions. It seems very difficult, but once you grasp it is extremely easy yet one of the most powerful tools when programming in PHP. I can’t count the number of times regex has saved me from hours of coding difficult text functions.

An Example

What would a good tutorial be without some real examples? Letกs first have a look at a simple email validation function. An email address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[azAZ09_\.\]+@[azAZ09\]+\.[azAZ09\\.]+$

Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this:

<?php

// Good email

$good = "[email protected]";

// Bad email

$bad = "blabla@blabla";

// Letกs check the good email

if (preg_match("/^[azAZ09_\.\]+@[azAZ09\]+\.[azAZ09\\.]+$/", $good)) {

echo "Valid email";

} else {

echo "Invalid email";

}

echo ก<br />ก;

// And check the bad email

if (preg_match("/^[azAZ09_\.\]+@[azAZ09\]+\.[azAZ09\\.]+$/", $bad)) {

echo "Valid email";

} else {

echo "Invalid email";

}

?>

The result of this would be กValid Email. Invalid Emailก, of course. We have just checked if an email address is valid. If you wrap the above code in a function, youกve got yourself a email validation function. Keep in mind though that the regex isn’t perfect: after all, it doesn’t check whether the extension is too long, does it? Because I want to keep this tutorial short, I won’t give the full fledged regex, but you can find it easily via Google.

Another Example

Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Letกs assume you want the numbers to be in the format of xxxxxxxxxx. The code would look something like this:

<?php

// Good number

$good = "1234567890";

// Bad number

$bad = "453423423";

// Letกs check the good number

if (preg_match("/\d{3}\d{7}/", $good)) {

echo "Valid number";

} else {

echo "Invalid number";

}

echo ก<br />ก;

// And check the bad number

if (preg_match("/\d{3}\d{7}/", $bad)) {

echo "Valid number";

} else {

echo "Invalid number";

}

?>

The regex is fairly simple, because we use \d. This basically means กmatch any digitก with the length behind it. In this example it first looks for 3 digits, then a กก (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.

What exactly is possible with Regular Expressions?

Regular expressions are actually one of the most powerful tools in PHP, or any other language for that matter (you can use it in your mod_rewrite rules as well!). There is so much you can do with regex, and weกve only scratched the surface in this tutorial with some very basic examples.

If you really want to dig into regex I suggest you search on Google for more tutorials, and try to learn the regex syntax. It isn’t easy, and thereกs quite a steep learning curve (in my opinion), but the best way to learn is to go through a lot of examples, and try to translate them in plain English. It really helps you learn the syntax.

In the future I will dedicate a complete article to strictly examples, including more advanced ones, without any explanation. But for now, I can only give you links to other tutorials:

The 30 Minute Regex Tutorial (http://www.codeproject.com/dotnet/RegexTutorial.asp)

RegularExpressions.info (http://www.regularexpressions.info/)

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.webdevarticles.com

[email protected]

This article was posted on March 28, 2005

by Dennis Pallett

How to Find Ideas for Articles & Speeches

How to Find Ideas for Articles & Speeches

by: Chirag Parmar

Do you have problems finding ideas for articles and speeches?

I know have had at times, and others tell me the same thing. At my Toastmasters club, for example, Iกve often heard members say they have difficulty finding topics for speeches.

But, Iกve learned, like others who write and speak a lot, to start with what I know. To use my own experiences or perspectives to make even a simple subject uniquely my own. And you can do the same.

Indeed, what seems mundane to you may fascinate someone else. Suppose, for example, you work in a fast food restaurant tell me about the best and worst customers, or tell me about the processes and training that make it possible to go from order to delivery in just a couple of minutes.

Hereกs a reallife example from my own experiences. I have a parttime job as a directory assistance operator for a telephone company, and that produces some interesting stories, like the time a woman called because the door knob to exit her borrowed apartment was broken, and she couldn’t figure out how to get out. She didn’t know who to call except Directory Assistance, and we had an interesting time figuring out a solution. Now thereกs a story to get an article or speech started, and perhaps even a theme such as กStrange but true stories from a directory assistance operator.ก

Then, thereกs the idea of providing insights for others. If you drive a truck, for instance, you might create a Top Ten list of common mistakes you see on the streets and highways. As a professional driver, you have special insight into the patterns of amateur drivers.

Beyond your personal experiences, think about issues that intrigue you. If you’re interested, doing research and thinking about a subject will be enjoyable and easy. Perhaps you can even satisfy your own curiosity as you prepare an article or speech that enlightens someone else.

These approaches should lead you to any number of story ideas. Make a list, of say five or ten possible topics. Now, ask yourself which of them will be the most enjoyable or easiest to develop. You also might ask yourself if you have enough examples to illustrate the points that fall under a specific topic.

Now, write an outline, to set out the main themes in your speech or article. By the time you finish outlining these themes, youกll probably have a number of new topics that could be developed into topics that stand on their own.

For example, looking back at the contents of this article so far, I see that discussing something others don’t know much about is one of the points. That would open the door to what I call the กEverybody knowsก syndrome, the unfounded assumption that others know what we know. Perhaps you think that your parenting experiences are just like everyone elseกs. Yet, your feelings may very well be unique and of great interest to other parents.

If all else fails, get ideas from others. For example, I subscribe to many online newsletters because I write a lot of articles myself. As potential story ideas come in I store them away in a folder, ready to be searched when I don’t have anything available in the top of my mind.

I can use the original article as the starting point, creating something new and unique by using my own experiences and ways of doing things. Or I can abstract someone elseกs article in my own words, again creating something new in the process. In both cases, Iกm creating something new based on my unique experiences or perspectives.

So, never be stuck for an idea for an article or speech! You already have enough experience and knowledge; itกs simply a matter of developing one of those ideas within that framework.

And hereกs a bonus: If you’re writing or speaking about something thatกs happened in your life, you won’t have to work hard to create the article or speech. Just follow the path through your memory.

About The Author

Chirag Parmar is 14 years old Indian boy. He is gujarati. Living in Mumbai. He is student but he likes to write this is why he is writing. he editor and content manager at his web site www.chiragparmar.tripod.com. Weekly free ezine: กWriter’s Heavenก filled with tips, subscribe it at http://groups.yahoo.com/group/chirag_parmar. Chirag manual กHow to write article?ก a four part series.Download it to learn how to writ? And for success, can be downloaded at: http://www.chiragparmar.tripod.com/howtowrite.html. Do you need free content for your website or ezine? Our archives deliver more than 270 freereprint articles available for your use. Send me email what type of article you want, then I will mail you more than 10 article.Email: [email protected]

This article was posted on April 11, 2004

by Chirag Parmar

How To Start A Profitable Online Business

How To Start A Profitable Online Business

by: Alvin Tan

Before you rush out to register a domain name, set up a website and declare that you are in business online, do you know where your revenue come from? Can the profit sustain the business and more importantly, giving you, the business owner, the rewards you wanted. In other words, what is the Business Model of your business? Is it profitable?

You may said, ขWhy do I need to know my business model? I just want to make money.ข Then I would ask you ขHow do you generate revenues? What are your costs? Who are your customers?ข Or you may have a great idea that you know everybody will be crazy over it. Then the next step you need to do is to find a suitable business model to start your business.

Basically the business model shows how a business will generate revenue by identifying its product offering, valueadded services, revenue sources and target customers. Some business models will fit naturally for a particular type of business. But with creativity and planning, you can add multiple new streams of revenue by combining several different models as part of your overall Internet business strategy. For example, a commonly seen strategy is for a content driven businesses to blend advertising with a subscription model.

Here are some of the successful business models found on Internet.

Affiliate Model

This model allow the merchant website to offer financial incentives for affiliated websites when they provide purchasepoint clickthrough to the merchant.

Example: Amazon.com

Brokerage Model

Brokers bring buyers and sellers together and facilitate transactions in exchange for a fee.

Example: eBay, Amazon.com, ClickBank

Advertising Model

Web advertising model is an extension of the traditional media broadcast model. The website provide content or service (like email, chat, forums, newsletters, search results) mixed with advertising messages.

Example: Yahoo!, Google, Overture, Hotmail

Merchant Model

Online wholesalers and retailers of goods and services, just like those in the offline world.

Example: Amazon.com, Victoriaกs Secret, Landsก End

Direct Sales Model

This model let the product or service creator to reach buyers directly and thereby compress the distribution channel.

Example: Dell Computer

Subscription Model

Users are charged a periodic fee (eg. daily, monthly or annual) to subscribe to a service or product

Example: America Online

The above models are not exhaustive or definitive. Internet business models continue to evolve. Expect to see new and interesting variations in the future.

About The Author

Copyright © 2005 Alvin Tan

Discover 19 Different, Killer Internet Business Models With Alvin Tan

Check Out The Ultimate Business Model here: http://www.UltimateBusinessModel.com/

This article was posted on February 03

by Alvin Tan

Psychological Tricks in Selling

Psychological Tricks in Selling

by: Stephen Bucaro

In this article, Iกm revealing six powerful secret psychological tricks that you can use to increase the effectiveness of your advertising and marketing. What if you don’t sell anything? Should you ignore this information?
You ARE selling something. Whether you are a Real Estate agent selling multimillion dollar homes, or a worker trying to sell your boss on the idea that you are a valuable employee, everybody is selling something. So it would be wise to learn these secret tricks and use them to achieve your own personal success.
The secret psychological tricks that I am going to reveal are not really secret. They have been used by shrewed salesman for millenium. Their existence was revealed back in 1984 by Dr. Robert Cialdini in his book กInfluence : The Psychology of Persuasionก.
You will recognize these tricks being used everywhere in advertising today. Now you will be able to put them to use to enhance your own personal success.
Psychological Selling Trick Number 1: Reciprocity
Reciprocity works like this: you give someone something of value for free. That individual feels an obligation to return the favor. Reciprocity is a very powerful principle.
To use reciprocity as a marketing tool, you give people something of value for free, they reciprocate by purchasing your product or service. But you would be surprised how many advertisers totally blow it. Either they don’t understand the concept of กfreeก, or they don’t have total faith in the principle of reciprocity.
For example, consider the offer กget a free camera when you subscribe to our magazine for two years.ก Thatกs not free. Or, กfree installation with a one year commitment.ก Thatกs not free. The customer is paying with an obligation. No sale.
Consider the offer,’receive the latest issue of our magazine absolutely free. No bill will be sent.ก If the prospective customer finds the magazine to be of value, they feel an obligation to subscribe. Or, กone month of free Internet service. No credit card required.ก If the Internet service performs well, the prospective customer feels an obligation to sign up.
The trick is to create something that has high perceived value to a prospective customer, but costs you little or nothing to produce. Free information is a good example. Here again many advertisers totally blow it. The free information turns out to be nothing more than blatant advertising.
Free samples of your product or service is another good example. Again, many businesses blow it. They either produce a cheaper version of their product to use as free samples, or they use the free sample campaign as a means to dump reject product.
The largest Internet Service Provider is well known for giving away hundreds of hours of service for free. No credit card required. The largest cookie company is famous for giving away free cookies. Reciprocity is a very powerful marketing strategy.
Psychological Selling Trick Number 2: Scarcity
Scarcity works like this: There is a limited amount of the item available. After those are gone, the item will not be available. กurgencyก implies Scarcity. For example, ‘this offer will be honored only for a limited timeก.
The effectiveness of the scarcity principle is well demonstrated by the large segment of the population involved in pursuing antiques, collectibles, and memorabilia simply because these items are scarce. Scarcity is often contrived, as when a company produces a กlimited editionก.
For example, when Disney releases a limit edition of one of its classic stories yes, limited to a production of more copies than they could ever possibly sell then it goes in the กvaultก. And how fortunate weกll be a few years from now when they decide to do us the favor of taking it back out of the vault.
Note: Manufactured items, especially DVDs and CDROMs, cannot be กscarceก. Itกs a simple matter to put the manufacturing dies back into production. All scarcities of manufactured items are contrived.
One popular incarnation of scarcity is the กgoing out of business saleก. Customers somehow don’t pick up on the fact that the markdowns are not that great, or that the store has new merchandise coming in the back door to take advantage of the increase in traffic.
Scarcity is a very powerful marketing tool. There are many ways to contrive scarcity. You can create a limited edition, or for items like information products, scarcity can exist in the form of urgency by creating a limited time offer.
Psychological Selling Trick Number 3: Commitment
Commitment involves getting a prospective customer to take a tiny step towards a goal. For example, you might get them to request free information, or fill out a survey. When the prospective customer takes that first step, they have made a commitment, however tentative, towards the goal you have set out for them. They are likely to take another step.
One example of this process is the ‘two stepก method used in mail order. When a mail order marketer runs an advertisement, they don’t even try to sell the product. Instead, the advertisement offers free information. A prospective customer makes that first commitment towards purchasing the product by requesting the free information. The free information they receive is designed to entice them to take the next step.
Another example of using commitment as a marketing tool is a survey. By checking a few boxes and answering a few questions, a prospective customer takes that first step towards a commitment. The result they receive from the survey is designed to entice them to take the next step.
Yet another example of using commitment as a marketing tool is a lottery. For example, people enter their name and address on a ticket for a chance to win a new car. A salesman uses that information to contact them. By entering their name and address on the lottery ticket, the individual has made a commitment to own that new car.
The most common example of the principle of commitment are those longwinded full page advertisements in magazines. The prospective customer invests a great deal of time reading through the entire advertisement. That investment of time represents a commitment. They are likely to take the next step, responding to the advertisement.
To use the psychological power of commitment in your advertising, don’t try to sell your product or service in your ad. Instead, use a survey, contest, or free information to get a prospective customer to make that first step towards a commitment to purchase your product.
Psychological Selling Trick Number 4: Consensus
Consensus involves getting prospective customers to believe that กeverybodyกs doing itก. Everybody is just waiting in line to purchase your product. Everybody can’t be wrong, so the product must be fantastic!
Of course you’re smart enough to know that everybody CAN be wrong. Everybody thought that SUVs were safe vehicles (they roll over). Everybody thought Enron was a great investment (it went bankrupt). Everybody thought Iraq had weapons of mass destruction (well maybe not everybody). You’re an independent thinker.
Here are some examples of headlines using the consensus principle: กItกs the new sensation crossing the countryก, กPeople are signing up in drovesก, กPeople just can’t get enough of themก, ‘record salesก, กUnbelievable response!ก and กJoin millions of smart consumersก. Combine this with a stock photograph of a large group of people, a long line of people, or a crowd of people, and you have a powerful consensus message.
Note: Many people don’t think they’re having fun unless they’re in a large, noisy crowd. Unfortunately, every large crowd contains a few lunatics. When things go wrong, the crowd stampedes and people get hurt, or killed. When I see a large crowd, I head the other way.
Fortuately, most people are not independent thinkers. They act like a herd of cattle. Use the consensus principle in your advertising, and people, like lemmings headed for the sea, will come in waves to buy your product.
Psychological Selling Trick Number 5: Authority
Authority involves getting prospective customers to believe that someone who is knowledgeable or famous uses your product or service. If a knowledgeable or famous person uses your product, then it must be fantastic!
The bigger the authority, the more powerful the advertising message will be. For example, doctors are authorities. กMost doctors prescribe Tylenol for arthritis painก. Large organizations are authorities. ‘the National Heart Association says Quaker oatmeal is good for your heart.ก The Federal Government is an authority. ‘the U.S. Food and Drug Administration says whole wheat bread is part of a complete dietก. If only we could think of a way to use God as an authority!
Hereกs how to use the principle of authority in advertising: search the Internet for any references to your product or service. Find an article that alludes to your product being of value. For example, letกs say you sell black Tshirts. You find an article by the U.S. Department of Agriculture that says กbees are attracted to bright colored clothingก. Your copy: ‘the U.S. Department of Agriculture that says my Tshirts protect you from attack by stinging insects.ก
Most advertising using the authority principle is taken out of context and exaggerated. Some advertising uses totally fake authorities. กMy dog biscuits are recommended by the International Association of Dog Nutritionistsก (an organization I started last week). Some advertising uses a กstudyก as an authority. กA recent study found that my lemonade tastes better than any other brandก (my mother liked it better).
I don’t recommend that you use a fake organization, a fake study, or take information out of context or exaggerate, but if you can locate a legitimate authority or study related in any way to your product and quote it without exaggeration, you will have a powerful authority message.
Psychological Selling Trick Number 6: Greed
Greed involves taking advantage of many peoples belief that there is a secret short cut to wealth. They believe that wealthy people didn’t earn their wealth, instead they know a กsecretก.
Note: I am not recommending that you use the principle of greed because it is used by unethical scammers. Iกm simply informing you of itกs existence in order to make this series of articles complete.
The simplest method of using the principle of greed is the chain letter. You have no doubt received a chain letter at some point. A chain letter contains a chart specifying the massive amounts of money the recipient will get when they follow the instructions. The first instruction is to send money.
The multilevel or network marketing scheme works similar to a chain letter. The prospective recruit gets a chart showing the massive amounts of money they will receive when they join the network. After parting with their money, the victim is instructed to con their friends and relatives into joining.
Another method of using the principle of greed is the lottery or casino. The odds of winning most lotteries are about the same whether you buy a ticket or not. A casino allocates only a tiny portion of itกs customers money to winnings in order to create the illusion that the odds of winning are good. Many people don’t understand statistics. In their mind, the phrase กwin a million dollarsก translates into กget a million dollarsก.
Another example of the principle of greed is the business opportunity scam. We know it works because successful scammers invest millions to run business opportunity infomercials, and they make hundreds of millions in profits. They prey on people who believe there is a secret short cut to wealth. The scammers think people who fall for their scam are stupid, lazy, and greedy, so they deserve to get ripped off.
The way to use the principle of greed is to contrive a กsecret planก. Run an ad describing how the plan requires absolutely no work to make massive amounts of money. Include a few bogus testimonials and a legitimate looking chart that shows the massive amount of money the plan will bring. Some scammers include pictures of fake checks or fake bank statements.
Never divulge any details of the plan in the ad. The prospective customer is required to send money to get the plan. The typical plan instructs the purchaser to run the same scam.
The principle of greed is very powerful. People who have been ripped of by this scam a thousand times before will, like hypnotized zombies, send you their money. They think THIS TIME they will receive the REAL secret plan.

Permission is granted for the below article to forward, reprint, distribute, use for ezine, newsletter, website, offer as free bonus or part of a product for sale as long as no changes are made and the byline, copyright, and the resource box below is included.

About The Author

Copyright(C)2004 Bucaro TecHelp.
To learn how to maintain your computer and use it more effectively to design a Web site and make money on the Web visit bucarotechelp.com.
To subscribe to Bucaro TecHelp Newsletter Send a blank email to [email protected]

This article was posted on July 28, 2004

by Stephen Bucaro

Broad, Phrase, Exact, Negative Four Google AdWor

Broad, Phrase, Exact, Negative Four Google AdWords terms you must know for advertising success

by: Rob Barrett

A few days ago, I was setting up my latest Google AdWords campaign. My brother was watching me work through the process, and he asked me:

กWhy do you put quotation marks and square brackets around some keywords?ก

I was a bit surprised to realise that I couldn’t actually answer him not in any definite way, at least. So, I set to work finding out what the matching options mean, and how they affect results.

First up is the default, Broad Match. This is where a keyword phrase is written as is, for example: google adwords

This method means that your Ad will potentially be shown to anyone searching for กgoogleก and กadwordsก, in any order and possibly with other terms. So, anyone searching for กadwords google helpก could see your Ad.

Next is Phrase Match. This is where a keyword phrase is enclosed by quotation marks, for example: กgoogle adwordsก

This is essentially the next step up from Broad Match your Ad could be shown to anyone searching for กgoogleก and กadwordsก, but only in that order, and possibly with other terms included in the search. So, กhow to start a google adwords campaignก could trigger your Ad to be shown.

The last in the กpositiveก matching options is Exact Match. This is where your keyword phrase is enclosed by square brackets, for example: [google adwords]

This is the most specific of the three types. In this case, your advert will only be shown if somebody searches for กgoogle adwordsก in that order and with no other terms.

These options each have their own merits, but generally, the more specific the search term, the higher your CTR (Click Through Rate).

If you have a small niche to start with, then Broad Match will give you the most exposure. The downside is that the large number of triggering phrases could push your CPC (cost per click) up, as a result of competition.

Larger markets require highlytargeted Ads, and this is where Exact Match (and Phrase Match, to an extent) comes into play. Imagine trying to get clicks from keywords such as กcar partsก compared to กford fiesta rear wheel bearingก. Obviously, the more specific your keyword terms, the more likely you are to get an interested visitor to your site.

The last of the keyword matching options is Negative Keyword. This is where a keyword is precluded by a minus sign, for example: tricks

This stops your Ad from being shown if somebody searches using that term. For example, กgoogle adwords tricksก would stop your Ad from being shown.

This is useful for prequalifying prospect clients if you are trying to sell something, then กfreeก would be a good term to include in your Keyword list.

Of course, as with any marketing campaign, which of these methods will work best for you is unpredictable, so always remember to test, test test!

If you need more help with setting up your Google AdWords campaign, this particular resource is one that I found useful when starting up:

Adword Equalizer (www.robbarrett.co.uk/recommendations_marketing/googleadwordequalizer.php)

Best of luck with your Google AdWords campaign!

About The Author

Rob Barrett is a professional web designer based in Dorset, England. To read more free articles on Internet Marketing and Google AdWords, visit: http://articles.robbarrett.com.

This article was posted on September 11

by Rob Barrett

PHP and Cookies; a Good Mix!

PHP and Cookies; a Good Mix!

by: Dennis Pallett

Introduction

Cookies have long been used in PHP scripts, and are a very useful function. But what exactly are cookies? Maybe you have used then, but you still don’t know exactly what they are. Or you are completely new to cookies? It doesn’t matter, because in this tutorial I will show you exactly what cookies are, and what they are used for.

Cookies in a nutshell

Cookies are small pieces of information that is stored on the computer of your visitors. Each browser handles it differently, but most simply store the information in a small text file. Internet Explorer has a special folder, which can be found in your C:\Windows or C:\Windows\System32 folder. You can delete all your cookies, by going to the Options and กClearing Cookiesก or deleting them by hand. I don’t recommend this though.

Almost every website uses cookies. If you go to Amazon.com, you will get several cookies. The same goes for CNN.com. Even Google uses cookies! They are extremely useful for (temporarily) storing information. For example, if you have a login system for your visitors, you could save their userid and password (very heavily encrypted!) so they are automatically logged in the next time they visit your website.

Or you could remember their last visit, and highlight everything that is new. And thatกs just the beginning.

Using Cookies

Using cookies in PHP is extremely easy. In fact, there is nothing to it, because of PHPกs inbuilt setcookie() function (http://php.net/setcookie). Have a look at the documentation, and then try the following example:

<?php

// Set a cookie

// Cookie name: name

// Cookie value: Dennis Pallett

// Cookie expire: in 24 hours

setcookie (กnameก, กDennis Pallettก, time() + (60*60*24));

?>

If you run the code above, then a cookie will be set. Thatกs all. The cookie name and value are pretty obvious. The cookie expire is when the cookie expires, or goes away. Simply use the time() function (http://php.net/time) and add the number of seconds you want to have the cookie available to it. In the example I added 60*60*24=86400 seconds, or 24 hours.

If you have looked at the documentation, you probably noticed there are additional arguments. As the documentation says, the path is to limit a cookie to a specific path on your web server. This is often used when you run multiple instances of the same script in separate directories. You can safely omit this argument when it doesn’t matter if the cookie is available sitewide.

There is also the domain argument. This can be used to limit the cookie to a specific subdomain, e.g. test.example.com. You can also safely ignore this argument, or set it to .example.com (note the beginning period, this is essential!).

Finally, there is also the secure argument. This argument is only used for cookies that are sent over a secure HTTPS connection (SSL). Just ignore this argument, unless you’re working with a secure connection.

One thing that should be mentioned is that cookies must be set, before you display any HTML/text. Itกs probably best if you turn on output buffering by putting ob_start() (http://php.net/ob_start) at the top of your page.

Now that you have set a cookie, you probably want to retrieve the value as well. After all, that is the whole point of using cookies. Thankfully, as PHP is ever so easy, you can retrieve the same way as you retrieve a GET value. See the following example to retrieve the value of the previous example:

<?php

echo กYour name is ก . $_COOKIE[กnameก];

?>

This should print "Your name is Dennis Pallett". Thereกs nothing more to it. Itกs just that easy!

Finally, one thing you probably want to do as well is remove cookies. This is as easy as setting them. Simply change the value of the cookie to FALSE, and change the expire date to 3000 seconds. See the following example:

<?php

setcookie (กnameก, FALSE, time()1000);

?>

Checking if cookies are enabled

Before you start using cookies, you must make sure your visitor has cookies enabled. This can be done with a simply PHP checking script. Unfortunately, the PHP page needs to reload to check for cookies. But this can be done very transparently, and your visitor should hardly notice anything.

The following example will first set a test cookie, then reload the page, and finally check whether cookies are enabled.

<?php

error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

// Check if cookie has been set or not

if ($_GET[กsetก] != กyesก) {

// Set cookie

setcookie (‘testก, ‘testก, time() + 60);

// Reload page

header ("Location: checkcookies.php?set=yes");

} else {

// Check if cookie exists

if (!empty($_COOKIE[‘testก])) {

echo "Cookies are enabled on your browser";

} else {

echo "Cookies are <b>NOT</b> enabled on your browser";

}

}

?>

Run the code above, and see what the output is. Check if cookies are enabled in your browser. If they’re not enabled, then you can enable them by going to your browserกs options. Unfortunately, this is different from each browser, so I can’t give you exact instructions. But Google can.

Storing Arrays

One feature of cookies that is often missed in articles is the ability to story arrays. Cookies can be used to store multidimensional arrays, which can be extremely useful to store data.

Consider the following code;

<?php

setcookie ("name[first]", "Dennis", time() + (60*60*24));

setcookie ("name[last]", "Pallett", time() + (60*60*24));

?>

You can then display these two cookies using the following code:

<?php

echo "First Name: " . $_COOKIE[กnameก][กfirstก];

echo "<br />Last Name: " . $_COOKIE[กnameก][กlastก];

?>

The cookie กnameก is an array, and has multiple values. You can even go deeper and have multidimensional arrays, e.g. $_COOKIE[กnameก][‘testก][กsomethingก][กvalueก]. You could store whole arrays of data in cookies. But beware that you don’t store too much data, there are certain size limits to cookies.

In Conclusion…

Cookies are really versatile, and can be used for a lot of different purposes. Many websites use cookies, and cookies can really make your website more personalized. Using cookies in PHP isn’t hard at all, and you should be able to use them without any difficulty.

Before actively using cookies in your website, you must check whether the visitor has enabled them in their browser. If they don’t have cookies enabled, you must either redirect to a noncookies version of your website, or you can make sure your website also works without cookies.

You can download a sample script at http://www.phpit.net/demo/php%20and%20cookies/logger.zip, where cookies are used in a (somewhat) practical way. In this example, there is a logging module, called log.php and a display module, called history.php. Basically, you include the log.php in other PHP pages, and then you can view history.php to lookup all the pages you have viewed and how often. The example uses arrays, and stores them in cookies.

The examples in this article can be downloaded at http://www.phpit.net/demo/php%20and%20cookies/examples.zip.

If you have a really unique practical way of using cookies, please let me know at dennis [AT] nocertainty [DOT] com. Iกd really like to hear about interesting ways of using cookies.

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.ezfaqs.com

This article was posted on December 06, 2004

by Dennis Pallett

Five Tips To Increase Your Sales

Five Tips To Increase Your Sales

by: Ed Hammen

1. You could end your ad copy with a discounted price. Just list your regular price and then offer a discounted price off the order ‘right now’. You could also offer a rebate that takes effect instantly. For example, you could say, กInstead of paying $99, you could order now and get an instant rebate of $20 you only pay $79!ก

2. You could end your ad copy with a free sample or trial of your product. If your ad didn’t attract them to buy, maybe a free sample or trial would. If you were selling an ebook, you could give them a free sample at the end of your ad copy. For example, you could say, กIf you’re still not sure about ordering, download a FREE sample chapter!ก

3. Use a กP.S.ก at the end of your ad copy. This is where you either want to repeat a strong benefit or use a strong close, like a free bonus. For example, กP.S. You can get (product), worth over ($), for the low price of ($)!ก Another example, กP.S. I can not guarantee the (No.) bonuses will be here tomorrow!ก

4. Make your visitors curious about your product by telling them they need to sign up to get into a password protected site to read the rest of the ad. This will give your product extra perceived value because it is so well guarded. Just like a diamond in a bank vault.

5. Motivate people to buy your product. Tell them positive things. For example, you could say, กYou can now reach your goals and change your life if you buy our product.ข If you come across positive in your ad copy, they will become positive about reaching their goals using your product.

About The Author

Ed Hammen is the owner of a couple of websites that provides valuable information on how to retire early by using your computer in the comfort of your own home.

http://www.onlinehomebasedbusiness.biz

http://www.ezinfocenter.com/8614146/SIM

[email protected]

This article was posted on November 26, 2004

by Ed Hammen

PHP OnTheFly!

PHP OnTheFly!

by: Dennis Pallett

Introduction

PHP can be used for a lot of different things, and is one of the most powerful scripting languages available on the web. Not to mention itกs extremely cheap and widely used. However, one thing that PHP is lacking, and in fact most scripting languages are, is a way to update pages in realtime, without having to reload a page or submit a form.

The internet wasn’t made for this. The web browser closes the connection with the web server as soon as it has received all the data. This means that after this no more data can be exchanged. What if you want to do an update though? If you’re building a PHP application (e.g. a highquality content management system), then itกd be ideal if it worked almost like a native Windows/Linux application.

But that requires realtime updates. Something that isn’t possible, or so you would think. A good example of an application that works in (almost) realtime is Googleกs GMail (http://gmail.google.com). Everything is JavaScript powered, and itกs very powerful and dynamic. In fact, this is one of the biggest sellingpoints of GMail. What if you could have this in your own PHP websites as well? Guess what, Iกm going to show you in this article.

How does it work?

If you want to execute a PHP script, you need to reload a page, submit a form, or something similar. Basically, a new connection to the server needs to be opened, and this means that the browser goes to a new page, losing the previous page. For a long while now, web developers have been using tricks to get around this, like using a 1×1 iframe, where a new PHP page is loaded, but this is far from ideal.

Now, there is a new way of executing a PHP script without having to reload the page. The basis behind this new way is a JavaScript component called the XML HTTP Request Object. See http://jibbering.com/2002/4/httprequest.html for more information about the component. It is supported in all major browsers (Internet Explorer 5.5+, Safari, Mozilla/Firefox and Opera 7.6+).

With this object and some custom JavaScript functions, you can create some rather impressive PHP applications. Letกs look at a first example, which dynamically updates the date/time.

Example 1

First, copy the code below and save it in a file called กscript.jsก:

var xmlhttp=false;

/*@cc_on @*/

/*@if (@_jscript_version >= 5)

// JScript gives us Conditional compilation, we can cope with old IE versions.

// and security blocked creation of the objects.

try {

xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (E) {

xmlhttp = false;

}

}

@end @*/

if (!xmlhttp && typeof XMLHttpRequest!=กundefinedก) {

xmlhttp = new XMLHttpRequest();

}

function loadFragmentInToElement(fragment_url, element_id) {

var element = document.getElementById(element_id);

element.innerHTML = ก<em>Loading …</em>ก;

xmlhttp.open("GET", fragment_url);

xmlhttp.onreadystatechange = function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

element.innerHTML = xmlhttp.responseText;

}

}

xmlhttp.send(null);

}

Then copy the code below, and paste it in a file called กserver1.phpก:

<?php

echo date("l dS of F Y h:i:s A");

?>

And finally, copy the code below, and paste it in a file called กclient1.phpก. Please note though that you need to edit the line that says กhttp://www.yourdomain.com/server1.phpก to the correct location of server1.php on your server.

<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.01 Strict//EN">

<html>

<head>

<title>Example 1</title>

<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">

function updatedate() {

loadFragmentInToElement(กhttp://www.yourdomain.com/server1.phpก, กcurrentdateก);

}

</script>

</head>

<body>

The current date is <span id="currentdate"><?php echo date("l dS of F Y h:i:s A"); ?></span>.<br /><br />

<input type="button" value="Update date" OnClick="updatedate();" />

</body>

</html>

Now go to http://www.yourdomain.com/client1.php and click on the button that says กUpdate dateก. The date will update, without the page having to be reloaded. This is done with the XML HTTP Request object. This example can also be viewed online at http://www.phpit.net/demo/php%20on%20the%20fly/client1.php.

Example 2

Letกs try a more advanced example. In the following example, the visitor can enter two numbers, and they are added up by PHP (and not by JavaScript). This shows the true power of PHP and the XML HTTP Request Object.

This example uses the same script.js as in the first example, so you don’t need to create this again. First, copy the code below and paste it in a file called กserver2.phpก:

<?php

// Get numbers

$num1 = intval($_GET[กnum1ก]);

$num2 = intval($_GET[กnum2ก]);

// Return answer

echo ($num1 + $num2);

?>

And then, copy the code below, and paste it in a file called กclient2.phpก. Please note though that you need to edit the line that says กhttp://www.yourdomain.com/server2.phpก to the correct location of server2.php on your server.

<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.01 Strict//EN">

<html>

<head>

<title>Example 2</title>

<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">

function calc() {

num1 = document.getElementById (กnum1ก).value;

num2 = document.getElementById (กnum2ก).value;

var element = document.getElementById(กanswerก);

xmlhttp.open("GET", กhttp://www.yourdomain.com/server2.php?num1=ก + num1 + ก&num2=ก + num2);

xmlhttp.onreadystatechange = function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

element.value = xmlhttp.responseText;

}

}

xmlhttp.send(null);

}

</script>

</head>

<body>

Use the below form to add up two numbers. The answer is calculated by a PHP script, and <em>not</em> with JavaScript. Whatกs the advantage to this? You can execute serverside scripts (PHP) without having to refresh the page.<br /><br />

<input type="text" id="num1" size="3" /> + <input type="text" id="num2" size="3" /> = <input type="text" id="answer" size="5" />

<input type="button" value="Calculate!" OnClick="calc();" />

</body>

</html>

When you run this example, you can add up two numbers, using PHP and no reloading at all! If you can’t get this example to work, then have a look on http://www.phpit.net/demo/php%20on%20the%20fly/client3.php to see the example online.

Any Disadvantages…?

There are only two real disadvantages to this system. First of all, anyone who has JavaScript turned off, or their browser doesn’t support the XML HTTP Request Object will not be able to run it. This means you will have to make sure that there is a nonJavaScript version, or make sure all your visitors have JavaScript enabled (e.g. an Intranet application, where you can require JS).

Another disadvantage is the fact that it breaks bookmarks. People won’t be able to bookmark your pages, if there is any dynamic content in there. But if you’re creating a PHP application (and not a PHP website), then bookmarks are probably not very useful anyway.

Conclusion

As Iกve shown you, using two very simple examples, it is entirely possible to execute PHP scripts, without having to refresh the page. I suggest you read more about the XML HTTP Request Object (http://jibbering.com/2002/4/httprequest.html) and its capabilities.

The things you can do are limitless. For example, you could create an extremely neat paging system, that doesn’t require reloading at all. Or you could create a GUI for your PHP application, which behaves exactly like Windows XP. Just think about it!

Be aware though that JavaScript must be enabled for this to work. Without JavaScript this will be completely useless. So make sure your visitors support JavaScript, or create a nonJavaScript version as well.

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.ezfaqs.com

[email protected]

This article was posted on November 28, 2004

by Dennis Pallett