Integrating WordPress with Twitter

Suppose I want to integrate my WordPress blog with Twitter or in other words I wish to tweet from my WordPress blog. I also want that my tweets on Twitter.com should appear as posts in my WordPress blog. For this purpose, I have chosen the Twitter Tools plugin by Crowd Favorite. You can have more information about this plugin from its site, http://crowdfavorite.com/wordpress/plugins/twitter-tools. On installing and activating this plugin, a message appears at the top of the Plugins page: Please update your Twitter Tools settings with a link to set the Twitter Tools options. Also in the Settings menu, one menu option is automatically added, Twitter Tools.  We can choose either way to set the Twitter Tools options. The Twitter Tools Options page appears as shown in below given figure. The page asks us to register our blog as an application on Twitter.com. The page also guides us about the options that we need to select in the registration page.

Twitter Tools Options page

The four blank boxes, Twitter Consumer Key, Twitter Consumer Secret, Access Token and Access Token Secret have to be filled with their respective values auto generated on registering our blog at Twitter.com. These values are required to make our plugin functional. So, let us proceed with the procedure of registering our blog by selecting the link, Twitter’s app registration page. This link navigates us to the Twitter Developer’s page where we are prompted to Sign In using our Twitter username and password. On entering a valid user name and password, we get a page to register our application. While registering our application, we can take the help of information displayed in above figure meant to guide us. Let us register our blog by entering the information as shown in below given figure.

Page to register our blog as an application at Twitter.com

On selecting the Register application button, we get a page displaying Twitter API Terms of Service. After reading the terms, we need to accept them to use the plugin. We get a page informing that our application has been registered successfully. The page also displays API key, Consumer Key and Consumer secret key. The page also displays a button, My Access Token that we select to get the Access Token and Access Token Secret values. We can copy and paste these auto-generated values in the respective boxes of Twitter Tools Options page (refer the first figure). After entering these values, we select the Connect to Twitter button to connect our WordPress blog to the Twitter.

The Twitter Tools Options displays a message confirming that our blog is connected to the Twitter. The Twitter Tools Options page displays a few more options to configure our plugin in detail. These options help us to:

  • determine whether to create a tweet when we post in our blog,
  • set the Tweet prefix for the new blog posts,
  • determine whether to create a blog post from our tweets,
  • select the category to assign to the tweet posts,
  • define tags for the tweet posts,
  • select an author for the tweet posts,
  • define the number of tweets to be shown in the sidebars, etc.

After choosing the desired options, we save them by selecting the Update Twitter Tools Options button. That is it; the Twitter Tools plugin is configured and fully functional. Now, if I tweet on Twitter.com (refer below given figure (a)), the tweet will appear as a blog post in our blog as shown in below given figure (b).

(a) Tweet at Twitter.com (b) Tweet appears in the form of post in the blog

Twitter Tools plugin adds an extra menu option, Tweet in Posts menu that can be used to create tweets when we post in our blog. On selecting the Tweet option from the Posts menu we get a Write Tweet page (below figure (a)) where we can write the message. The message not only appears as a blog post on our blog but also appears as a tweet on Twitter.com (below figure (b)).

(a) Writing Tweet in our blog (b) Tweet written in the blog appears in Twitter.com

To display our latest tweets and to tweet from our sidebars, we can make use of the Twitter Tools widget that is automatically added to the Widgets page on successful installation of the Twitter Tools plugin. So, let us open the Widgets page by selecting the Appearance->Widgets option from the main navigation menu and drag the Twitter Tools widget from the Available Widgets list and drop it on either of the sidebars. Let us set the title of the widget to My Tweets (below figure (a)) and select the Save button to save the widget. In our blog, we find that our latest tweets appear along with a textbox allowing us to tweet from our blog’s sidebars as shown in below given figure (b).

Note: The textbox to tweet appears in the sidebars only when the administrator is logged in.

(a) Options of Twitter Tools Widget (b) Latest tweets and textbox to tweet in the sidebars

For more information, refer my book, Blogging with WordPress 3 for Beginners available at Amazon.

Installing WordPress Locally

WordPress requires a web server with PHP support, a URL rewriting module and an instance of MySQL. The URL rewriting module that understands .htaccess directives is required for the purpose of getting search engine friendly URLs. WordPress generates search engine friendly URLs also called permalinks through URL rewriting modules. Hence, the servers such as Apache or IIS7 providing URL rewriting are popularly used for installing WordPress.

The installation process is quite simple. We need a server software (MAMP, XAMP or WAMP) and a WordPress package (download it from wordpress.org) and follow the below given steps:

  • Install a local server (Mac: MAMP, PC:XAMPP or WAMP). Figure 1 displays XAMPP control panel that automatically appears on successful installation of XAMPP. We can see that Apache and MySQL both are in running mode.

Note: Mac OS X comes with an Apache web server (with PHP and URL rewriting).

Figure 1. XAMPP Control Panel

  • Next, we have to create a new database. Select the Admin button besides MySQL from XAMPP control panel to open phpMyAdmin. In the Create new database textbox, enter the name of the new database as wordpress_local (any) followed by selecting the Create button as shown in Figure 2. After creating the database, the next thing we have to do is to set the password of the root. We will be using the user, root (that has all the privileges by default) to access the newly created database. By default, when we install XAMPP, there is no password set for the root. To set the password of the root, select Privileges link from the top (Figure 2). We get a User overview page displaying the list of default users. Select the Edit privileges icon for the root on localhost. We get a box to specify password for the root. Lets enter the password for the root as mce (any text)

Note: The phpMyAdmin is a free software tool written in PHP that manages the administration of MySQL over the World Wide Web. It helps us perform variety of database manipulation tasks quite easily.

Figure 2. Creating MySQL database through phpMyAdmin

  • Extract the downloaded WordPress package in a folder say blog (or any other name). Copy the blog folder containing the WordPress files into the root directory of our server, i.e., in its htdocs folder.
  • In the blog folder, we will see that besides other files, WordPress package provides a template configuration file also. The configuration file is named wp-config-sample.php. First, we have to rename the wp-config-sample.php file to wp-config.php and then update it to specify the information (db_name, user, password, host) of the newly created database, wordpress_local in it. Hence, open the wp-config.php file and search for the following three lines:

define(‘DB_NAME’, ‘database_name_here’);

define(‘DB_USER’, ‘username_here’);

define(‘DB_PASSWORD’, ‘password_here’);

and modify them to appear as shown below:

define(‘DB_NAME’, ‘wordpress_local’);

define(‘DB_USER’, ‘root’);

define(‘DB_PASSWORD’, ‘mce’);

where wordpress_local is the database we just created through phpMyAdmin, root is the default user with all privileges and mce is the password that we have set for the root through phpMyAdmin. Save the wp-config.php file after making these changes.

  • Open the browser and point it at the URL, http://localhost/blog/wp-admin/install.php to begin the WordPress installation process. The word, blog appears in the URL because we have renamed the WordPress package directory to blog before copying it on our web server’s root directory. On doing this, we get a Welcome page asking information for the blog that we want to create. The page represents the beginning of the WordPress’s five minute installation process. We enter the title of the blog, name, password and email address of the administrator in the respective textboxes as shown in Figure 3. Also, select the checkbox, Allow my site to appear in search engines like Google and Technorati if we are making a blog that is open for public and finally select the Install WordPress button.

Figure 3. Page showing WordPress’s five minute installation process

We get a Success message (Figure 4) declaring that WordPress is successfully installed on our local server. If we enter administrator’s name and password and select the Log In button, the Dashboard of our blog opens up to administer our blog. Later in this chapter, we will understand Dashboard and its role in administering a blog.

Figure 4.  Page confirming successful installation of WordPress

To visit our newly created blog, open the browser and point it at the address, http://localhost/blog/. Our blog is displayed with a default post, Hello world! provided by WordPress as shown in Figure 5.

Figure 5. Blog displaying the default post Hello world!

In order to open the login page again, point the browser to the following address, http://localhost/blog/wp-login.php

For more information, refer my book, Blogging with WordPress 3 for Beginners available at Amazon.

WordPress book for Beginners

Blogging with WordPress 3 for Beginners : A Practical Guide to build and maintain your own blog

If you’ve ever wanted to learn how to build and maintain your own blog, Blogging with WordPress 3 for Beginners is for you! This book will lead you through all the building blocks necessary for a fully functional blog in WordPress platform.


The book covers :
• Different ways of installing WordPress
• Creating and managing blog contents through Posts and Pages
• Managing Media, Links and Comments
• Managing Themes, Custom Menus and Widgets.
• Managing user accounts, roles and setting profiles
• Extending features of blog through plugins.
• Using Tools and Settings
• Using Press This tool to grab web pages found on the net
• Importing contents from different blogging platforms
• Exporting the WordPress blog contents
• Submitting posts via email and through desktop client
• Generating search engine friendly URLs
• Translating blog contents into different languages
• Integrating blog with Facebook and Twitter
• Taking Online Backup
• Generating XML Sitemaps and displaying advertisement for revenue

Available at Amazon

Sending radio and checkbox options to the server asynchronously

In usually every web application checkbox and radio button play a major role in getting the information from the user. In this article, we will learn to send the asynchronous messages of the selected checkboxes and radio boxes to the server.

For this article, we will be creating three files:

  • checkboxradioajax.php – PHP script that will display three radio buttons and three checkboxes for the user to select from.
  • checkboxradioajax.js – JavaScript file that create XMLHttpReqest object and that send the information of the selected checkboxes and radio buttons to the server asynchronously
  • checkboxradiodata.php – Server side PHP script that displays information about the selected checkboxes and radio buttons to the client as a server response

Coding for “Sending radio and checkbox options to the server asynchronously”

The code in checkboxradioajax.php file is as under :

checkboxradioajax.php

<html>

<head>

<script type=”text/JavaScript” src=”checkboxradioajax.js”></script>

</head>

<body>

Choose one : <br>

<input name=”drink” value =”Hot Coffee” onClick=’display()’> Hot Coffee  <br>

<input name=”drink” value =”Cold Coffee” onClick=’display()’> Cold Coffee <br>

<input name=”drink” value =”Soft Drink” onClick=’display()’> Soft Drink <br><br>

Choose all the options that you want to have : <br>

<input name=”food” value =”Hot Dog” onClick=’display()’> Hot Dog  <br>

<input name=”food” value=”Pizza” onClick=’display()’>Pizza   <br>

<input name=”food” value=”Noodles” onClick=’display()’>Noodles  <br>

<input name=”food” value=”Chips” onClick=’display()’>Chips  <br><br>

<div></div>

</body>

</html>

Above program defines three radio buttons with options : Hot Coffee, Cold Coffee and Soft Drink  and four checkboxes with options : Hot Dog, Pizza, Noodles and Chips. The name assigned to the radio buttons is “drink” and if any of the radio button is selected, display() method will be invoked. Similarly the checkboxes are named : “food” and if any of the checkbox is selected, same display() method will be invoked. Beside this,  a <div> element is defined with id : “info”  for displaying the server response. Remember, that we can select only one radio button in a group whereas any number of checkboxes can be selected in a group.

The code in JavaScript file, checkboxradioajax.js file is as under :

checkboxradioajax.js

1.        function makeRequestObject(){

2.        var xmlhttp=false;

3.        try {

4.        xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’);

5.        } catch (e) {

6.        try {

7.        xmlhttp = new

8.        ActiveXObject(‘Microsoft.XMLHTTP’);

9.        } catch (E) {

10.      xmlhttp = false;

11.      }

12.      }

13.      if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {

14.      xmlhttp = new XMLHttpRequest();

15.      }

16.      return xmlhttp;

17.      }

18.      function display()

19.      {

20.      var xmlhttp=makeRequestObject();

21.      ControlsArray=document.getElementsByTagName(‘input’);

22.      var fooditms=”";

23.      var drinkitms=”";

24.      for(var i=0; i< ControlsArray.length; i++)

25.      {

26.      if(ControlsArray[i].type==”checkbox” && ControlsArray[i].checked)

27.      {

28.      fooditms+=ControlsArray[i].value + ” “;

29.      }

30.      if(ControlsArray[i].type==”radio” && ControlsArray[i].checked)

31.      {

32.      drinkitms+=ControlsArray[i].value + ” “;

33.      }

34.      }

35.  xmlhttp.open(‘GET’, ‘checkradiodata.php SelectedDrink=’+drinkitms+’&SelectedFood=’+fooditms, true);

36.      xmlhttp.onreadystatechange=function() {

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

38.      var content = xmlhttp.responseText;

39.      if( content ){

40.      document.getElementById(‘info’).innerHTML = content;

41.      }

42.      }

43.      }

44.      xmlhttp.send(null)

45.      }

Explanation of the above program

Statements from 1-17 are making an XMLHttpRequest object.

21.   ControlsArray=document.getElementsByTagName(‘input’);

The elements in the web page with name : “input” (usually all the elements in a web page come under this category) are searched and all the items with this name are assigned to an array : ControlsArray.

22.   var fooditms=”";

23.   var drinkitms=”";

24.   for(var i=0; i< ControlsArray.length; i++)

25.   {

26.   if(ControlsArray[i].type==”checkbox” && ControlsArray[i].checked)

27.   {

28.   fooditms+=ControlsArray[i].value + ” “;

29.   }

30.   if(ControlsArray[i].type==”radio” && ControlsArray[i].checked)

31.   {

32.   drinkitms+=ControlsArray[i].value + ” “;

33.   }

34.   }

With the help of a loop, all the elements in the ControlsArray are checked one by one and the value of all the elements in the array which are of type “checkbox” and are checked (selected) are stored in a variable fooditms. Similarly, all of the elements of type “radio” and are checked, their values is assigned to variable drinkitms

35. xmlhttp.open(‘GET’, ‘checkradiodata.php?SelectedDrink=’+drinkitms+’&SelectedFood=’+fooditms, true);

36.  xmlhttp.onreadystatechange=function() {

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

38.  var content = xmlhttp.responseText;

39.  if( content ){

40.  document.getElementById(‘info’).innerHTML = content;

41.  }

42.  }

43.  }

44.  xmlhttp.send(null)

45.  }

XMLHttp request is made to the  server (by GET method) for the file checkboxradiodata.php, sending all the selected drink items and selected food items (stored in variables drinkitms and fooditms respectively) to it.

The state and the response to asynchronous request are checked. If the value of readyState property becomes 4 and the value of the status of the HTTP Request is 200, the response is then retrieved from the response stream and is assigned to variable : content which is then applied to the innerHTML property of the element with id : “info” to display the response from the server (i.e. to display all the items selected from the checkbox and radio buttons).

The instruction : xmlhttp.send(null) is used to actually send the request to the server. And if we don’t want to pass any query string with the requested file,  the argument passed to this method is null or else it contains the query string.

Remember, the response generated by the server is based on the execution of the file : checkboxradiodata.php. Lets analyze what it returns

checkboxradiodata.php

<?php

$food=$_GET['SelectedFood'];

$drink=$_GET['SelectedDrink'];

if($drink==”")

{

echo “You have not selected any drink <br><br>”;

}

else

{

echo “The drink selected is : ” . $drink . “<br><br>”;

}

if($food==”")

{

echo “You have not selected food <br><br>”;

}

else

{

echo “The types of Food selected are : ” . $food . “<br><br>”;

}

?>

The selected food items and selected drink items are retrieved from $_GET array and stored in variables $food, and $drink respectively. The list of items selected from checkboxes and radio buttons are passed to this file  while making the XMLHttp request for the file using following command :

35.    xmlhttp.open(‘GET’, ‘checkradiodata.php?SelectedDrink=’+drinkitms+’&SelectedFood=’+fooditms, true);

We can see in above instruction that selected drink item and the selected food items are passed to the checkboxradiodata.php file. The retrieved items in $food and $drink variables are displayed on the screen (in case the contents of the variable are non blank or else the message : “You have not selected” food or dink is displayed).

Output of “Sending radio and checkbox options to the server asynchronously”

If both drink as well as food items are selected, the output may appear as shown below :

Output if both drink and food items are selected

This finishes my article on “Sending radio and checkbox options to the server asynchronously”

For more information, refer my book: “Developing Web Applications in PHP and AJAX” available at: http://www.amazon.com/Developing-Web-Applications-PHP-AJAX/dp/0070707103/ref=ntt_at_ep_dpt_4

Frequently Used HTML Properties

In this article, we will learn about few HTML properties like, Color, Font and Margin :

Color

The color property is used for setting the color of text.

Syntax:

color: value;

The value can be specified in any of the following ways:

* We can specify colors by their English names. The standard color names are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.

* Colors can also be defined as an RGB triplet in hexadecimal format i.e. the combination of Red, Green, and Blue color values. The lowest value is 0 (hex 00) and t highest value is 255 (hex FF)

Example:

“#00FF00″

It represents colors as hexadecimal numbers for red, green and blue. The first two characters following the # give the number for red, the next two for green and the last two for blue. These numbers are always in the range 0 to 255 decimal. Above example designates dark green color

Font

The font property is used for setting the font family, size, style and weight of the desired element. The font property includes the following properties:

Font-Family

The font-family property is for setting the font to be displayed in an element.

Example:

font-family: Verdana;

The element to which this property is applied will appear in Verdana font

The value of this property can be any font like verdana, sans-serif, arial, courier etc;

Font-Size

The font-size property is for setting the size of the text used in an element.

Syntax:

font-size: value;

where the value can be any of the following:

* xx-large

* x-large

* larger

* large

* medium

* small

* smaller

* x-small

* xx-small

* length

* % (percent)

Examples:

font-size: xx-large;

font-size: small;

Out of the above font size values, length and % (percent) needs explanation. Both are used for specifying the font size in units.  CSS provides us four different units to specify the font size:

* “Ems” (em) The “em” is a scalable unit that is equal to the current font-size. That is, if the if the current font-size of the document is 12pt, then 1em is equal to 12pt. Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc.

* Pixels (px) – Pixels are fixed-size units used to define the resolution of the computer screen One pixel is equal to one dot (smallest unit) on the computer screen. The size in pixels cannot be scaled up or down.

* Points (pt) – Points are usually used for defining size of printable documents. One point is equal to 1/72 of an inch.

* Percent (%) – The percent unit is much like the “em” unit. If the current font-size of the document is 12 pt, then font size of 100% means 12pt. The benefit of using the percent unit is that the text can be scaled up as well as down.

Note: Both the em and percent units get larger as the base font-size increases, but pixels and points do not.

Examples:

font-size:12px;

font-size:120%;

Font-Style

The font-style property is for setting the style of the text in a desired element.

Syntax:

font-style: value;

where values can be any of following:

* normal

* italic

* oblique

Font Weight

The font-weight property is for specifying the weight of text in a desired element.

Syntax:

font-weight: value;

where value can be any of the following:

* lighter

* normal

* 100 .. 900

* bold

* bolder

Examples:

font-weight:bold;

font-weight:300;

font-weight:lighter;

Margin

The margin property declares the margin between an HTML element and the elements around it. This property can be set for the top, left, right and bottom of an element. It includes the following four properties: margin-top, margin-left, margin-right and margin-bottom to specifying the margins for the top, left, right and bottom of the element respectively.

Syntax:

margin-(top/left/right/bottom): value;

where value can be specified in terms of length, percentage or auto. The length can be specified in terms of px (pixels), pt (points), in(inches) etc.

Examples:

margin-top:10px;

margin-top:.3in;

We can also specify all the four margins of an element in a single property: margin

With margin property, we can specify the top, left, right and bottom margin of an elements simultaneously. The sequence of specifying the four margins is as follows: top, right, bottom and left.

Example:

margin: 10px 10px 10px 10px;

If we want to specify the same margin on all sides, we can even specify a single value to be applied for all sides.

Example:

margin: 10px;

First Step to learn CSS Styles

In this article you will learn the application of Internal style sheets for giving dynamic appearance to the web pages. The Style sheets are a collection of styles popularly used for applying uniform formatting to the web site.

Styles is a term that denotes the combination of different fonts, colors, back-grounds etc. that can be applied to the web contents to highlight some important information and to make the web site as a whole more attractive.

The Style Sheets properly known as Cascading Style Sheets (CSS) is a style language developed and maintained by World Wide Web Consortium (W3C). Its main purpose is to apply dynamic layout and appearance to the documents written in a markup language. As said earlier, a style sheet contains several styles. Cascade here means application of more than one style onto an HTML element simultaneously.

In the Style sheet, the styles are written in the form of rules where every rule is a combination of a selector and declaration.

Let us see one rule:

H1{color:red;font-family:arial;margin:1.0in}

Above rule is a combination of a selector and declaration. The selector is the name of the HTML element to which declaration is applied i.e. H1 element in above rule is a selector. The declaration is a collection of property and value pairs separated by colons. Like in above rule, color is a property and red is its value. If there is more than one declaration in a rule, they are separated by ; (semi colon). The list of style properties in declaration are bracketed by { and }.

Syntax of rule:

selector { attribute: value, value…. attribute: value, value… etc.}.

Note: In the HTML file, we can define our own selectors with the help of ID and Classes.

The Cascade Style Sheets (CSS) can be used either internally or externally i.e. they can be either embedded inside an HTML file or can be written in a separate file that is then inked to the HTML file.

Using Internal Style Sheet to apply style to H1 element

The style sheet can be written internally within the HTML file or externally in a separate file. The styles written in internal Style sheet can be applied to only the same HTML file in which it is included. For internal Style Sheet, you need to simply place the CSS code (rules) within the <head></head> tags of the HTML file to which we want to apply the styles as shown below :

<style/css>

H1{color:red;font-family:arial;margin:1.0in}

</style>

The rule is a collection of property and value pairs and we can use any number of properties in a rule. In above example we have used three properties: color, font-family and margin but we may use any. We will just see the usage of these properties.

We see that the style rules are written between the <style> and </style> tags in case of internal style sheet. In above statement, we have used a single rule consisting of combination of selector and declaration. The selector is H1 as we want to apply style to this element(s) of the HTML file  and the declaration is color:red;font-family:arial;margin:1.0in. The declaration consists of three sets of properties and their values though we can use any number of property and value pairs. The color property will make the H1 element to appear in red color, font-family property will set the font of the H1 element to arial font and the margin property will make the H1 element to appear at the distance of 1 inch from the top and left border of browser window .

A compete HTML file with the internal Style Sheet that applies style to H1 element may appear as :

<html>

<head>

<style type=text/css>

H1{color:red;font-family:arial;margin:1.0in}

</style>

<title>Styles Examples</title>

</head>

<body>

<H1>Believe in God</H1>

</body>

</html>

The thing to remember is that the style rules have to be written between  <style> and </style> tags. To see how H1 element appears on application of style, we need to open the HTML file with the help of a browser and we will see that the text enclosed in between <H1> and </H1> tags appears as shown in Figure 1 with all the properties: color, font-family and margin applied to it.

Style applied on H1 tag

Figure 1 Style applied on H1 tag

Creating Database Table In PHP

In this article, we will learn to create a database table in a MySQL database through PHP script. Following are the steps that we will follow to create a database table:

1. Establishing connection with MySQL server
2. Creating a database (if it does not exists). If database already exists then skip this step
3. Selecting the database (in which table is to be created).
4. Writing SQL statement for creating a table
5. Executing the SQL statement
To understand above steps let us look at the following program that creates a table by name: products in shopping database. The products table that we are going to create will have five fields (columns): id, item_code, item_name, quantity and price. The fields: id, item_code and quantity are considered to be of int (integer) data type, item_name of character data type and price of float data type.
Coding for “Creating Database Table In PHP”
createtable_products.php
<?php
$user=”username”;
$password=”password”;
$connect = mysql_connect(“localhost”, $user, $password) or die (“Please check your server connection.”);
//create the database if it doesn’t already exist
$create = mysql_query(“CREATE DATABASE IF NOT EXISTS shopping”) or die(mysql_error());
mysql_select_db(“shopping”);
$sql = “CREATE TABLE products(
id int(6) NOT NULL auto_increment,
item_code int(4),
item_name varchar(50),
quantity int(4),
price float)”;
$res = mysql_query($sql) or die (mysql_error());
echo “products table successfully created!”;
?>
Above program has all the five steps of creating a table. In the first two lines, two variables $user and $password are initialized to the username and password of the MySQL server respectively. From the 3rd line onwards, we see that the five steps for creating a table are executed. Let us see look at each statement step by step:
1. Establishing connection with MySQL server
Before proceeding with creation of a database or a table, the first thing we need to connect with MySQL server. The connection is established with the help of a valid user name and password.
$connect = mysql_connect(“localhost”, $user, $password) or die (“Please check your server connection.”);
In above command localhost signifies that MySQL server is installed on the local machine. The string localhost will be replaced by the IP address of the server or server name (Example : sqlserver.com or 216.237.120.79 ) in case we try to connect with the remote server. The $user and $password variables contain the valid userid and password supplied by the administrator. The keyword die is for displaying error messages if any information supplied is wrong.
2. Creating a database
After we are connected to the MySQL server, we must then create the database (if it does not exists) followed by selecting it i.e. making it active in memory. The command for creating database is :
$create = mysql_query(“CREATE DATABASE IF NOT EXISTS shopping”) or die(mysql_error());
Above statement is creating a database by name “shopping” (in case it doesn’t already exists). If the database is already there, this command won’t do anything
3. Selecting the database
Selecting the database means loading the database in memory (i.e. making it active). The command for selecting a given database is :
mysql_select_db(“shopping”);
Above command is selecting the database: shopping. Now all SQL statements that are executed will be applied to the tables belonging to this (shopping) active database.
4. Writing SQL statement for creating the table
The below given SQL statement creates a table by name products that has five fields out of which id field is set to auto_increment i.e. its value  will automatically increase by 1 with every record inserted
$sql = “CREATE TABLE products(
id int(6) NOT NULL auto_increment,
item_code int(4),
item_name varchar(50),
quantity int(4),
price float)”;
The rest of the fields (columns) in the table are item_code that will store an integer values of almost 4 digits, item_name field will store the name of the item of up to 50 characters long and quantity field can store an integer value of up to 4 digits and price field can store a fractional value (value with decimal points)
5. Executing the SQL statement
Below given statement executes the above SQL statement of creating the products table
$res = mysql_query($sql) or die (mysql_error());
The $res variable is for storing the result of the execution of the SQL statement
For more information, refer my book: “Developing Web Applications in PHP and AJAX” available at: http://www.amazon.com/Developing-Web-Applications-PHP-AJAX/dp/0070707103/ref=ntt_at_ep_dpt_4

Different Methods of sending data from one PHP script to another

When we want some feed back from the user on some subject or want some information to be supplied by the user, we take the help of forms. A form consists of certain input elements to accept user data that is then passed to another PHP script for further processing on selecting Submit button. In this article, we will learn different HTTP Request methods like GET and POST that are used for sending data from one PHP script to another.

<form action=”display.php” method=”get”>

Name: <input type=”text” name=”name” />

Age: <input type=”text” name=”age” />

<input type=”submit” />

</form>

Above form has two input boxes named “name” and “age”. The form “action” points to a php file : “display.php” and the “method” is “get”. Meaning the contents of the form will be submitted to php script : “display.php” using the HTTP request-method GET for further processing.

The information is passed from one PHP script to another using any of the following two HTTP Request methods :

  • GET
  • POST

GET

In this method the information passed is less secure as it is displayed in the browser’s address bar and moreover, there is a limit on the amount of information passed (it can be of maximum 100 characters).

POST

In this method, the information passed is more secure as it is not displayed in the browser’s address bar.

$_GET array

The $_GET array is an array where data from the previous form sent using HTTP GET method are stored. The data from the previous form is sent in the form of pairs : variable name(s) and its value(s).

Recall that information sent from a form with the GET method is less secure as it is displayed in the browser’s address bar and also the size of the information passed is limited.

When the user clicks the “Submit” button, the URL sent will look something like this:

http://localhost/display.php?name=john&age=22

We can see that when we use the GET method, all the information passed is attached in the browser address bar after the ? mark.

The target file : “display.php” file can now extract the data from $_GET array using following statements :

Welcome <?php echo $_GET["name"]; ?>.<br>

Your age is <?php echo $_GET["age"]; ?>

The name and age sent from the source PHP script is accessed from $_GET array and displayed .

$_POST array

The $_POST array is an array which collects the values sent from a form using HTTP POST method.

Example :

<form action=”display.php” method=”post”>

Enter your name: <input type=”text” name=”name” />

Enter your age: <input type=”text” name=”age” />

<input type=”submit” />

</form>

When the user clicks the “Submit” button, the $_POST["name"] and $_POST["age"] variables will be automatically set by PHP. The $_POST array contains all POST data and the URL will not display any form data (so it is more secure).

The destination PHP script : “display.php” file can now use the $_POST array to retrieve the form data with the help of following code :

Welcome <?php echo $_POST["name"]; ?>.<br>

Your age is <?php echo $_POST["age"]; ?>

Note : Information sent from a form with the POST method is invisible to others and also there is no limit to the amount of information sent.

To conclude : HTTP POST method is a better way of transmitting data because :

  • Variables sent with HTTP POST are not shown in the URL
  • Variables have no length limit

$_REQUEST array

$_REQUEST array contains the contents of both $_GET and $_POST. That is, it is used to collect the information from a form which is sending data by either method : GET or POST method.

So, in case we are not known of HTTP method used by the source PHP script, it is a wise decision to access the information using $_REQUEST array. The target file : display.php made in the earlier examples can be rewritten as :

Example :

Welcome <?php echo $_REQUEST["name"]; ?>.<br />

Your age is <?php echo $_REQUEST["age"]; ?>

It will access the information sent from the source PHP file sent by any method : GET or POST

For more information, refer my book: “Developing Web Applications in PHP and AJAX” available at: http://www.amazon.com/Developing-Web-Applications-PHP-AJAX/dp/0070707103/ref=ntt_at_ep_dpt_4

Matching the Password and Confirm Password Fields in jQuery

In this article, we are going to learn how to validate Password and Confirm Password fields of a form. That is, we will learn  to confirm that the passwords entered by the user in the two fields : Password and Confirm Password fields exactly match.

HTML file for “Matching the Password and Confirm Password Fields in jQuery”

Let us make an HTML file that displays three labels and three text fields for Userid, Password and Confirm Password as shown below:

<body>

<form>

<div><span>User Id </span><input  /></div>

<div><span>Password </span><input name=”password” /><span> Password cannot be blank</span></div>

<div><span>Confirm Password </span><input class=”confpass” /><span class=”error”> Password and Confirm Password don’t match</span></div>

<input value=”Submit”>

</form>

</body>

In the HTML file, the label messages User Id, Password and Confirm Password  are enclosed in span elements that are assigned class names: ‘label’. The input text fields are assigned the respective class names ‘userid’, ‘password’ and ‘‘confpass’  for retrieving the data entered in them via jQuery . Finally, all the input text fields are followed by the error message nested inside the span element of class ‘error’.

The reasons of assigning the classes to all the items items: label, error message and submit button is to automatically apply the properties defined in the class selectors ‘.label’,  ‘.error’ and ‘.submit’ (defined in the style sheet: style.css). Also, the combination of label, input text field and error are nested inside the div element so that we can apply style property to div element to creating spacing among each combination of label, input text field and error message.

The style sheet with the respective class selectors is as shown below:

style.css

.label {float: left; width: 120px; }

.error { color: red; padding-left: 10px; }

.submit { margin-left: 125px; margin-top: 10px;}

div{padding: 5px; }

In the style sheet file, the class selector: ‘.label’ contains the float property set to value: ‘left’ so as to make the label appears on the left side of the browser window (creating space for the input text field to appear on its right) and the width property is set to value 120px to define the width that the label can consume. The class selector ‘.error’ assigns the red color to the error messages  and for making the error message appear at the distance of 10px from the element on its left. The class selector ‘.submit’ contains the margin-left property set to value: 125px and margin-top property set to value:10px to make it appear at the distance of 125 px from the left border of the browser window (to appear below the input text fields) and at the gap of 10px from the element just above it. The type selector ‘div’ has the padding property set to value: 5px for creating some space among the div elements where each div element contains a combination of label, input text field and error message

The jQuery code to test that data entered in the Password and Confirm Password fields are exactly same is as shown below :

$(document).ready(function() {

$(‘.error’).hide();

$(‘.submit’).click(function(event){

data=$(‘.password’).val();

var len=data.length;

if(len<1)

{

$(‘.password’).next().show();

}

else

{

$(‘.password’).next().hide();

}

if($(‘.password’).val() !=$(‘.confpass’).val())

{

$(‘.confpass’).next().show();

}

else

{

$(‘.confpass’).next().hide();

}

event.preventDefault();

});

});

Before we understand the jQuery code, let us understand the usage of .next() method that is used in it:

.next()

This method retrieves the next following sibling in the specified element. Remember, this method returns the very next sibling for each element and not all next siblings like nextAll() method does

Syntax:

.next(selector)

where selector is an optional parameter used for specifying the selector expression for matching with the specified elements

Code for “Matching the Password and Confirm Password Fields in jQuery”

In the jQuery code, initially, we hide the error messages (elements nested inside the span element of class ‘error’). Thereafter, we attach a click event to the submit button. In the event handling function of the click event, we retrieve the data in the Password field (input text field of class ‘password’) and store it in variable ‘data’. If the length of the contents in variable ‘data’ is found less than 1  i.e. if user has not entered anything in the Password field, we make the element next to the password field (which is span element of class ‘error’) to appear on the screen i.e. we display the error message: ‘Password cannot be blank’  on the screen.

If the user has not left the password empty, we check whether the data entered in the password field and the Confirm password field (data in elements of class ‘.password’ and ‘.confpass’) are exactly the same. If the two don’t match, we display the error message (which is the element next to the Confirm Password field): ‘Password and Confirm Password’ don’t match’ on the screen. We also invoke the preventDefault() method of the event object to prevent the data entered by the user  from sending it to the server as we are mainly interested in just confirming that the data entered in Password and Confirm Password fields match

On execution of jQuery code, if we leave the Password field blank and select Submit button, we get the error message: ‘Password cannot be blank’  on the screen as shown in below given figure :

Error message appears if password is not entered

If the contents of Password and Confirm Password fields don’t match, we get the error message: ‘Password and Confirm Password don’t match’ as shown in below given figure

Error message appears if password and confirm password don’t match

This finishes my article on “Matching the Password and Confirm Password Fields in jQuery”

For more information, refer my book : “jQuery Recipes A Problem-Solution Approach” available at : http://www.amazon.com/jQuery-Recipes-Problem-Solution-Approach-Development/dp/1430227095/ref=sr_1_1?ie=UTF8&s=books&qid=1287320549&sr=8-1

More articles :

Forward Navigation Via Toolbar Buttons

Sending List box option to the server asynchronously

In this article, we will learn how multiple items selected from the list box are sent to the server asynchronously.

For this article, we will make three files namely:

  • listajax.php – PHP script that will display a list box
  • listajax.js – JavaScript file that creates XMLHttpRequest object to send request to the server asynchronously. The options of the list box selected by the user are passed to this JavaScript file
  • showlistdata.php – Server side PHP script to display the response i.e. the options of the list box selected by the user

Coding for “Sending List box option to the server asynchronously”

The coding of listajax.php is as under :

listajax.php

<html>

<head>

<script type=”text/JavaScript” src=”listajax.js”></script>

</head>

<body>

Choose one or more category: <br>

<select multiple=”multiple” size=”4″ onblur=’itemdisplay()’ >

<option value=”Camera” selected>Camera</option>

<option value=”Mobile”>Mobile</option>

<option value=”Book”>Book</option>

<option value=”Computer”>Computer</option>

<option value=”Washing Machine”>Washing Machine</option>

<option value=”Refrigerator”>Refrigerator</option>

</select><br><br>

<div id=”info”></div></body>

</html>

Above program creates a list box with name “Category” with six items : Camera, Mobile and Book, Computer, Washing Machine and refrigerator displayed in it. The multiselect feature of the listbox is set with the help of “multiple” attribute. So, user can select more than one item from the list box (by pressing Ctrl key). After selecting the item(s), the moment user presses tab key or clicks anywhere else on the web page i.e. when the focus of the listbox is lost, a method : itemdisplay() is invoked. Beside this,  a <div> element is defined with id : “info”  for displaying the server response

The coding of the JavaScript file, listajax.js is as under :

listajax.js

1.       function makeRequestObject(){

2.       var xmlhttp=false;

3.       try {

4.       xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’);

5.       } catch (e) {

6.       try {

7.       xmlhttp = new

8.       ActiveXObject(‘Microsoft.XMLHTTP’);

9.       } catch (E) {

10.    xmlhttp = false;

11.    }

12.    }

13.    if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {

14.    xmlhttp = new XMLHttpRequest();

15.    }

16.    return xmlhttp;

17.    }

18.    function itemdisplay()

19.    {

20.    var xmlhttp=makeRequestObject();

21.    optionsArray=document.getElementById(‘Category’).options;

22.    var selectedArray = new Array();

23.    var x=0;

24.    for(var i=0; i< optionsArray.length; i++)

25.    {

26.    if(optionsArray[i].selected)

27.    {

28.    selectedArray[x]=optionsArray[i].value;

29.    x++;

30.    }

31.    }

32.    var cat=”";

33.    for(var i=0;i<selectedArray.length;i++)

34.    {

35.    if( i!=selectedArray.length -1) {

36.    cat +=selectedArray[i]+”,”;

37.    }

38.    else

39.    {

40.    cat+=selectedArray[i];

41.    }

42.    }

43.    xmlhttp.open(‘GET’, ‘showlistdata.php?&Category=’+cat, true);

44.    xmlhttp.onreadystatechange=function() {

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

46.    var content = xmlhttp.responseText;

47.    if( content ){

48.    document.getElementById(‘info’).innerHTML = content;

49.    }

50.    }

51.    }

52.    xmlhttp.send(null)

53.    }

Explanation of the above program

Statements from 1-17 are making an XMLHttpRequest object.

21.       optionsArray=document.getElementById(‘Category’).options;

The element in the web page with name : “Category” (our listbox) is searched and all the items available in it are assigned to an array : optionsArray.

22.       var selectedArray = new Array();

23.       var x=0;

24.       for(var i=0; i< optionsArray.length; i++)

25.       {

26.       if(optionsArray[i].selected)

27.       {

28.       selectedArray[x]=optionsArray[i].value;

29.       x++;

30.       }

31.       }

With the help of a loop, all the elements in the optionsArray are checked one by one and all the items selected by the user are stored in a separate array : selectedArray.

32.       var cat=”";

33.       for(var i=0;i<selectedArray.length;i++)

34.       {

35.       if( i!=selectedArray.length -1) {

36.       cat +=selectedArray[i]+”,”;

37.       }

38.       else

39.       {

40.       cat+=selectedArray[i];

41.       }

42.       }

All the items stored in array : selectedArray (containing only the list of items selected by the user ) are retrieved and stored in a variable cat (after separating them by commas except the last one)

43.       xmlhttp.open(‘GET’, ‘showlistdata.php?&Category=’+cat, true);

44.       xmlhttp.onreadystatechange=function() {

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

46.       var content = xmlhttp.responseText;

47.       if( content ){

48.       document.getElementById(‘info’).innerHTML = content;

49.       }

50.       }

51.       }

XMLHttpRequest request is made to the  server (by GET method) for the file showlistdata.php, sending all the item(s) selected by the user (stored in variable cat) to it. The selected item list sent to the requested file will be retrieved in showlistdata.php file using $_GET array.

The state and the response to asynchronous request is checked. If the value of readyState property becomes 4 (meaning the request is complete) and the value of the status of the HTTP Request is 200 (which means there is no error), the response is then retrieved from the response stream and is assigned to variable: content which is then applied to the innerHTML property (property  used to display results) of the element with id : “info” to display all the items that are selected by the user in the list box

Again the response generated by the server is based on the execution of the file : showlistdata.php. Lets analyze what it returns

showlistdata.php

<?php

echo “The categories of items selected are : ” . $_GET['Category'] ;

?>

Above file returns the text : “The categories of items selected are “ and the category name(s) selected by the user. The categories selected by the user are passed to this file while making the XMLHttpRequest for the file by following command :

43.  xmlhttp.open(‘GET’, ‘showlistdata.php?&Category=’+cat, true);

Output of “Sending List box option to the server asynchronously”

On executing the file, listajax.php we get a list box with several options as shown in below given figure :

Selecting various items by pressing tab key.

We can select as many category of items as we want followed by pressing tab key. All the categories selected are displayed separated by commas as shown in below given figure.

Selected items are displayed

For more information, refer my book: “Developing Web Applications in PHP and AJAX” available at: http://www.amazon.com/Developing-Web-Applications-PHP-AJAX/dp/0070707103/ref=ntt_at_ep_dpt_4

Here are few  links of my published articles :

Iphone Application to Read And Set Slider’s Value

Validating Date Through Jquery

How to Validate an Email Address Through Jquery

Validating select element in jQuery

Selecting Multiple options in Select element using jQuery

Mobile Web Development using jQTouch:Session Management