Tag Archives: synapse india jobs

SynapseIndia Part 4 – Displaying Data Php Development


So far in this tutorial, you have created a database and put information into it. In this part I will show you how to create an input page for your database, and how to display the whole contents.

HTML Input

Inputing the data using HTML pages is almost identical to inserting it using a PHP script. The benefit, though, is that you do not need to change the script for each piece of data you want to input and you can also allow your users to input their own data.

The following code will show an HTML page with textboxes to enter the appropriate details:

<form action=”insert.php” method=”post”>
First Name: <input type=”text” name=”first”><br>
Last Name: <input type=”text” name=”last”><br>
Phone: <input type=”text” name=”phone”><br>
Mobile: <input type=”text” name=”mobile”><br>
Fax: <input type=”text” name=”fax”><br>
E-mail: <input type=”text” name=”email”><br>
Web: <input type=”text” name=”web”><br>
<input type=”Submit”>

This page could, of course, be formatted and have other changes made to it. It is just a basic form to get you started. Next you will need to edit the script from last week. Instead of using information to input into the database, you will instead use variables:


@mysql_select_db($database) or die( “Unable to select database”);

$query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”;


This script should then be saved as insert.php so that it can be called by the HTML form. It works because, instead of the data being entered locally, it is being entered into the form and stored in variables which are then passed to the PHP.

You could also add to this script a message confirming the data input. This is basic PHP, though, and you should read the PHP tutorial if you do not know how to do this.

Outputting Data

Now you have at least one record, if not many more, in your database you will be wanting to know how you can output this data using PHP. Before beginning, though you should be familiar with loops in PHP (you can find out about them in the tutorial on Free Webmaster Help) as they are used for this way of outputting data.

The first command you will need to use is a MySQL query made up like this:

SELECT * FROM contacts

This is a basic MySQL command which will tell the script to select all the records in the contacts table. Because there will be output from this command it must be executed with the results being assigned to a variable:

$query=”SELECT * FROM contacts”;

In this case the whole contents of the database is now contained in a special array with the name $result. Before you can output this data you must change each piece into a separate variable. There are two stages to this.

Counting Rows

Before you can go through the data in your result variable, you must know how many database rows there are. You could, of course, just type this into your code but it is not a very good solution as the whole script would need to be changed every time a new row was added. Instead you can use the command:


This will set the value of $num to be the number of rows stored in $result (the output you got from the database). This can then be used in a loop to get all the data and output it on the screen.

Setting Up The Loop

nYou must now set up a loop to take each row of the result and print out the data held there. By using $num, which you created above, you can loop through all the rows quite easily. In the code below, $i is the number of times the loop has run and is used to make sure the loop stops at the end of the results so there are no errors.

while ($i < $num) {



This is a basic PHP loop and will execute the code the correct number of times. Each time $i will be one greater than the time before. This is useful, as $i can be used to tell the script which line of the results should be read. As the first line in MySQL output is 0, this will work correctly.

Assigning The Data To Variables

The final part of this output script is to assign each piece of data to its own variable. The following code is used to do this:


So to take each individual piece of data in our database we would use the following:


We do not need to get the ID field (although we could have done) because we have no use for it in the current output page.

Combining The Script

We can now write a full script to output the data. In this script the data is not formatted when it is output:


@mysql_select_db($database) or die( “Unable to select database”);
$query=”SELECT * FROM contacts”;



echo “<b><center>Database Output</center></b><br><br>”;

while ($i < $num) {


echo “<b>$first $last</b><br>Phone: $phone<br>Mobile: $mobile<br>Fax: $fax<br>E-mail: $email<br>Web: $web<br><hr><br>”;



SynapseIndia Part 3 – Inserting Information Php Development


Over the past two parts I have explained what I am planning to do in this tutorial and have shown you how to create a database to use with the tutorial. In this part I will be showing you how to insert some information into your database so that it is more useful.

Connecting To The Database

The first thing you must do before you can do any work at all is to connect to the MySQL database. This is an extremely important step as, if you are not connected, your commands to the database will fail.

Good practice for using databases is to specify the username, password and database name first so that if you change any of them at a later date you will only have to change one line:


At this point you may be wondering if it is a security risk, keeping your password in the file. You don’t need to worry, though, because the PHP scource code is processed aby the server before being sent to the browser so it is impossible for the user to see the script’s source.

Next, you will need to issue the command to start a database connection:


This line tells PHP to connect to the MySQL database server at ‘localhost’ (localhost means the server that the site is running one. Unless you web host tells you otherwise you should use localhost. If you are given a server address (such as sql.myserver.com you should replace localhost with “sql.myserver.com” (including the quotes)) using the username stored in $username and the password in $password.

Before I show you how to work with the database, I will show you one more command:


This is a very important command as it closes the connection to the database server. Your script will still run if you do not include this command but too many open MySQL connections can cause problems for a web host. It is good practice to always include this line once you have issued all your commands to the database, to keep the server running well.

Selecting The Database

After you have connected to the database server you must then select the database you wish to use. This must be a database to which your username has access. The following command:

@mysql_select_db($database) or die( “Unable to select database”);

is used to do this. This tells PHP to select the database stored in the variable $database (which you set earlier). If it cannot connect it will stop executing the script and output the text:

Unable to select database

This extra ‘or die’ part is good to leave in as it provides a little error control but it is not essential.

Executing Commands

Now you have connected to the server and selected the database you want to work with you can begin executing commands on the server.

There are two ways of executing a command. One is to just enter the command in PHP. This way is used if there will be no results from the operation.

The other way is to define the command as a variable. This will set the variable with the results of the operation.

In this part of the tutorial we will use the first way as we are not expecting a response from the database. The command will look like this:


The useful thing about using this form of the command is that you can just repeat the same command over and over again without learning new ones. All you need to do is to change the variable.

Inserting Data

For this part of the tutorial I will return to the contacts database which we created in the last part. We will now add our first information to the database:

First: John
Last: Smith
Phone: 01234 567890
Mobile: 00112 334455
Fax: 01234 567891
mail: johnsmith@gowansnet.com
Web: http://www.gowansnet.com

This will all be put in with one command:

$query = “INSERT INTO contacts VALUES (”,’John’,’Smith’,’01234 567890′,’00112 334455′,’01234 567891′,’johnsmith@gowansnet.com’,’http://www.gowansnet.com&#8217;)”;

This may look a little confusing at first so I will explain what it all means.

Firstly $query= is there because we are assigning this to the variable $query (see the section above). The next part:


is quite easy to understand. It tells the PHP to insert into the table called contacts the values in the brackets which follow.

The part in the brackets contains all the information to add. It uses all the fields in order and inserts the information from between the quotes. For example:


will be inserted into the 2nd field which, in this table, is the ‘first’ field.

You may have noticed that you are not inserting any value into the first field in the database (id). This is because this field is going to act as an index field. No two records in the database will have the same ID. Because of this, when we set up the database we set ID to ‘Auto Increment’. This means that if you assign it no value it will take the next number in the series. This means that this first record will have the ID 1.

SynapseIndia Php Development – File Write

Now that you know how to open and close a file, lets get on to the most useful part of file manipulation, writing! There is really only one main function that is used to write and it’s logically called fwrite.

php – file open: write

Before we can write information to our test file we have to use the functionfopen to open the file for writing.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

php – file write: fwrite function

We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite’s first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you’re good to go!

Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);

The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second containedTracy Tanner. After we finished writing we closed the file using the fclose function.

If you were to open the testFile.txt file in NOTEPAD it would look like this:

Contents of the testFile.txt File:

Bobby Bopper
Tracy Tanner

php – file write: overwriting

Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing filetestFile.txt and write some new data into it.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);

If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto

In the next lesson we will show you how to get information out of a file by using PHP’s read data function

SynapseIndia Php Development – ile close

The next logical step after you have opened a file and finished your business with it is to close that file down. You don’t want an open file running around on your server taking up resources and causing mischief!

php – file close description

In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it’s a good programming practice and because we told you to!

php – file close function

In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

The function fclose requires the file handle that we want to close down. In our example we set our variable “$fileHandle” equal to the file handle returned by thefopen function.

After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.

SynapseIndia Installing Apache and PHP Development under Win32 – Page 2

Stop Apache, if it isn’t already. Copy php4ts.dll to the Windows\System directory. In httpd.conf search for #LoadModule it should bring you to a list of modules that can be loaded. Leave those alone, but directly under them, add these lines:
LoadModule php4_module c:/php/sapi/php4apache.dll
AddType application/x-httpd-php .php
Now, write a file called test.php, with this as the content:
echo "PHP Rules!";
Save the file, and put it into the directory you set as the document root. You set that up above. Now start up Apache, and type this into the location bar of your favorite web browser:
If all goes well, you should get a lovely:
PHP Rules!

SynapseIndia Installing Apache and PHP Development under Win32

If you are on this site, we’re sure that you already know that PHP is a server side web programming language. Its purpose is very similar to ASP, but in my opinion, it’s better. There are more databases available to use with it and ASP can only communicate with Access and SQL servers. PHP can communicate with SQL Server, MySQL, mSQL, and several others, but that is not the topic of this tutorial.
What’s Apache?
Apache is a web server, similar to PWS, and IIS. They, and it, listen(s) on a specific port (usually it’s 80) and allow you to run a website off of your home computer. Neat, Eh?

Installing Apache

First you need to download Apache Do that here. It’s fairly large (about 3.6mb), so be patient. After downloading, double click the exe. Installing is a breeze, but configuring isn’t that easy.

Configuring Apache
Move to your apache directory after installing. It’s usually C:\Program Files\Apache Group\Apache. Look for, and open, a folder called conf. Open the file called httpd.conf. It may look cryptic and confusing at first, but about half the file is made up of comments, which begin with a “#” mark.The parts in red need to be found, and the parts in green need to be changed or added. (NOTE: I removed all the file comments for the sake of size – those comments shown below are there just as a guide for you.)

DocumentRoot "C:/website"

#NOTE: you can change c:/website 
#to anything you want, that is just 
#happens to be where I store my files. 
#Another NOTE: All slashes must be forward /
<Directory />
    Options FollowSymLinks ExecCGI
    AllowOverride None

<Directory "C:/website">
    Order allow,deny
    Allow from all

After changing that, place a file (we’ll call ours filename.htm) to the document root you set. Then start Apache (by clicking Start button -> Program Files -> Apache -> Management -> Start Apache). Now use your favorite browser, and type in:
You should get your file. Cool. If so, keep reading. If not, then email me and tell me what the problem is. Be sure to send the complete httpd.conf file.
Installing PHP
This part is fairly easy, the PHP homepage is php.net, you can download the PHP 5.2.3 installer here. This file is quite big too. So, again, be patient. Now, unzip the file to C:\php.


SynapseIndia Email Forms in PHP Development

Barebones PHP basics

A couple very basic concepts of PHP must be discussed before getting into this project further. First, PHP code is inserted into pages inside <?php and ?> tags. Second, any page that contains any amount of those tags should have the a file extension of either .php, .php3, .php4, or .php5. The .php3 extension is for pages that are using features that were new to version 3 of PHP, and so on. Check with your system administrator for any rules regarding which extension you need to use and the tags you need to enclose the code, because PHP is also designed to be custom configured to fit the way you are comfortable coding. It can be configured to use the ASP <% %> tags amongst other customizations that are beyond the scope of this article.
PHP pages can still contain a lot of typical HTML, so your pages will still need the basic <html>, <body>, etc. tags. They just may not be right at the top like you are used to seeing because there may be PHP variables and such being defined before the <html> tag. Also, if you do a view source at the client level, you will only see the HTML and client-side scripting, because by that time all the PHP has been read and processed by the server and the resulting HTML is fed to the browser.
With all that being understood, let’s get on with the fun stuff.

The Form

Like any email form, the original form itself is quite simple. No great shakes here, just a standard HTML form with a POST method and the action pointing to the PHP page that will process the form results.
<form name="form" method="post"
<p class="bodymd">Your Name<br>

<input type="text" name="Name">
<p class="bodymd">Your Email<br>
<input type="text" name="Email">
<p class="bodymd">Comments or Questions<br>
<textarea name="Comments" rows="5" cols="40">

<p class="bodymd">
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Reset" value="Clear Form">
The file extension for the page this form is on can be .html, .shtml or whatever you choose; the page that the results are handed to, however, must be a PHP page.

Processing the Mail

Let’s t ake a look at the code [ PHP code for email form. ]. It is very typical of any scripting language — server-side or client-side, so if you have any amount of knowledge in JavaScript, ASP, JSP, Perl or the like, it should seem very familiar.
The code is a combination of validation and email processor. Take a look at the first ifstatement, it is checking to see if any of the fields are empty. If any one field is, it then opens a form and prints a statement to inform the user that they missed a required field(s).
The statements after that are also simple. The if statements check each of the individual fields to see if they are empty; if they are empty, the script prints that field again to be filled in (note that the form was already opened above if a field was empty). If it is not empty it then stores the value of that field in a hidden field.
The final if statement above is again checking for empty fields. If any of the required fields are empty, it will print submit and clear buttons as well as the closing form tag to complete the form that has been opened earlier for re-submission. Once re-submitted it will be re-validated by the same process. Once all of the required fields are filled in, it then hits the elseoption of the last if statement. This is where the mail is processed and sent.

Compiling and Sending the Email

Look at the else in the final if statement:
	$message = "Name: $Name\nEmail: $Email\nComments: $Comments\n";
	$extra = "From: $Name\r\nReply-To: $Email\r\n";
	mail ("noone@nowhere.com", "Website Email", $message, $extra);
	echo "<p class=bodymd>Thanks for your inguiry, $Name.</p>";
	echo "<p class=bodymd>A response will be sent to
   $Email as soon as possible.</p>";
The first line sets the body of the email. This is where it takes the values of all the fields, which are variabilized with the field name preceded by a “$,” so the field name “Name” is known to PHP as $Name. The \n starts the text on the next line. Therefore, $message = "Name: $Name\nEmail: $Email\nComments: $Comments\n"; will result in this message body:
Name: {value of Name field}
Email: {value of Email field}
Comments: {value of Comments field}
The second line is not necessary to send email, but it is convenient to use, as it sets the “from” and “reply-to” fields in your email client. It’s a neat feature.
Now sending the email, you won’t believe how easy this is. All it takes is:
mail ("noone@nowhere.com", "Website Email", $message, $extra);
The “mail” statement sends the defined values to the sendmail program configured in your Web server. The first value is where the email gets sent to, the second is the subject of the email, the third is the body of the message that you complied above, and the last is the “from” and “reply-to” statement from above … thats it!
Now how easy was that?!