Introduction into PHP and MySQL
The main sources are PHP-manual (www.php.net) and MySQL-manual (www.mysql.com).
What is PHP?
PHP is a scripting language integrated into HTML which is interpreted and accomplished on server. It’s simple to show this on the example:
<html>
<head>
<title>Example</title>
</head>
<body>
<?php echo "Hi, I'm a PHP script!"; ?>
</body>
</html>
Having accomplished this script we’ll get a page in which will be written following:
Hi, I'm a PHP script!
It’s rather simple and useless.
The main difference from CGI-scripts written in other languages like Perl or C is that in CGI-programs you write HTML-code yourself and using PHP you integrate your program into ready-made HTML-page by usage of opening and closing tags (<?php and ?> in the example).
Difference PHP from JavaScript is that PHP-script is accomplished on server and the result of work is transmitted to a customer; in JavaScript code is completely transmitted to the client machine and only there it is accomplished.
Fans of Internet Information Server will discover that PHP has very much in common with Active Server Pages (ASP) and Java enthusiasts will say that PHP is much like Server Pages (JSP). All these three languages allow placing code accomplished on Web-server inside of HTML-pages.
PHP abilities
To say in some words, on PHP everything is possible that can be done by means of CGI-programs. For example, such actions are available: handling data from form, generation of dynamic pages, obtaining and sending cookies.
Besides that support of many data bases is included in PHP which makes Web-applications writing with data bases usage extremely simple.
Here is an incomplete list of the data bases supported:
Adabas D
InterBase
Solid
dBase
mSQL
Sybase
Empress
MySQL
Velocis
FilePro
Oracle
Unix dbm
Informix
PostgreSQL
Besides that PHP understands transactions IMAP, SNMP, NNTP, POP3 and even HTTP and also has an ability to work with sockets and communicate with other transactions.
Brief history of PHP
Autumn 1994 can be considered the PHP beginning; at that time Rasmus Lerdorf decided to widen abilities of his Home-page and write a runner for simplest tasks accomplishment. Such runner was ready by the beginning of the year 1995 and was called Personal Home Page Tools. It cannot do too much – it only understood the simplest language and some macros.
In the middle of year 1995 the second version appeared which was called PHP/FI Version 2. FI additional attachment was taken from another Rasmus parcel which was able to interpret forms (Form Interpritator). PHP/FI was compiled inside of Apache and used standard API Apache. PHP-scripts proved to be faster than the analogical CGI-scripts as far as the server has no necessity in generating a new process. Abilities of PHP-language are close to those of Perl which is the most popular language for CGI-programs writing. Support of many well-known data bases was added (for example, such as MySQL and Oracle). Interface to GD-library enabled generating pictures on a tape. From this moment PHP/FI became widespread.
At the end of year 1997 Zeev Suraski and Andi Gutmans decided to rewrite the internal runner in order to correct interpritator’s errors and increase scripts accomplishment speed. In half a year on 6th June 1998 a new version appeared which was called PHP 3.
By summer of year 1999 PHP 3 has been included into some commercial products. According to the data of NetCraft by November 1999 PHP has been used in more than 1 million domains.
Why you are to choose PHP
There is no need in telling web-applications’ developers that web-pages are not only pictures and text. Site which is worth consideration must keep some user-interactive level: information search, products sale, conferences and so on. Traditionally all this has been realized by CGI-scripts written in Perl. But CGI-scripts are scaled rather badly. Every new CGI-call demands from core a new process generation and this takes processor time and spends main memory. PHP offers another variant – it functions like a part of web-server which makes it similar to ASP from Microsoft.
PHP-syntax has very much in common with that of C or Perl. People who know programming can start writing PHP-programs fast. There is no strict data typification and no need in memory allotment/ memory release in this language.
Programs written in PHP are rather easy to read. Unlike Perl-programs codes written in PHP is easy for visual reading and understanding.
Drawbacks of PHP
PHP is an interpreted language and thus its speed cannot be compared with this of compiled C. However by writing small programs which is usual for PHP-projects when the whole project consists of small pages with code overheads connected with loading in the memory and call of a CGI-program written in C start their action. The ready-made modules base isn’t as large as that of, for example, CPAN by Perl. It cannot be helped – it’s just a question of time. In PHP4 special repository PEAR which has analogy with CPAN has been beforeseen by developers and I think that in the nearest future sufficient modules number for its filling will be written.
What is MySQL
MySQL is a compact multithreaded server of data bases. MySQL is significant through great speed, resistance and easy usage.
MySQL was developed by TcX company for internal needs which concluded in rapid handling of very big data bases. The company affirms it has been using MySQL since 1996 on server with more than 40 data bases which contain 10 000 tables from which more than 500 contain more than 7 million columns.
MySQL is an ideal solution for small and medium applications. Server sources are compiled on many platforms. The most completely server abilities are expressed on Unix-servers where multithread support exists which results into considerable increase of productivity.
At the present moment MySQL is still being developed although 3.22 versions are completely capable of working.
MySQL-server is free of charge for non-commercial usage. Otherwise you should buy a license which costs 190 EUR.
Abilities of MySQL
MySQL supports language of SQL-requests in standard ANSI 92 and beside that it has a lot of extensions to this standard which no other data base possesses.
A brief list of MySQL-abilities:
- Unlimited users’ number is supported that work simultaneously with data base.
- Number of columns in a table can reach 50 million.
- Fast command accomplishment. MySQL is likely to be the fastest server from all the already existing ones.
- Easy and effective safety system.
In fact MySQL is a very fast server but to reach this its developers had to sacrifice some demands to relative data base operation system. Following items are absent in MySQL:
- Integrated requests support like SELECT * FROM table1 WHERE id IN (SELECT id FROM table2).
- Transaction support isn’t realized. Instead of this you are offered to use LOCK/UNLOCK TABLE.
- No triggers and saved procedures support.
According to creators’ words these items enabled reaching high promptitude. Their realization decreases server speed considerably. These abilities aren’t critical when creating web-applications which combined with high promptitude and low price enabled server to gain great popularity.
Examples of PHP usage
Working with forms
In this example easiness of HTML-forms data handling is shown.
Let’s create a simple HTML-file.
<HTML>
<HEAD>
<TITLE>Request for information </TITLE>
<BODY>
<CENTER>
Do want to know more about our goods?
<P>
<TABLE WIDTH = 400><TR><TD align = right>
<FORM ACTION="email.php" METHOD="POST">
Your name :<BR> <INPUT TYPE="text" NAME="name" SIZE="20" MAXLENGTH="30">
<P>
Your email:<BR> <INPUT TYPE="text" NAME="email" SIZE="20" MAXLENGTH="30">
<P>
I am interested in:
<SELECT NAME="preference">
<OPTION value = "Apples">Apples
<OPTION value = "Oranges">Oranges
</SELECT>
<P>
<INPUT TYPE="submit" VALUE="Send a request!">
</FORM>
</TD></TR></TABLE></CENTER>
</BODY>
</HTML>
We’ll call this file request.html. In it we’ve indicated that given forms will be handled with file email.php. Here are its contains:
<?
/* This script obtains variables from request.html */
PRINT "<CENTER>";
PRINT "Hallo, ".$_POST['name'];
PRINT "<BR><BR>";
PRINT "Thank you for your interest. <BR><BR>";
PRINT "You are interested in ".$_POST['preference'].",
Information about them will be sent to you on e-mail: ".$_POST['email'];
PRINT "</CENTER>";
?>
Now if user calls request.html and types into the form name ‘John’ and e-mail: john@doe.com and says he is interested in ‘Apples’ and after that clicks ‘Send a request!’, email.php will be called as an answer which puts out on the screen something like this:
Hi, John!
Thank you for your interest.
You are interested in Apples. Information about them will be sent to you on e-mail: john@doe.com
Now we are to keep promise and send an e-mail.
There is function MAIL in PHP for this.
Syntax: void mail(string to, string subject, string message, string add_headers)
to – email recipient address.
subject – subject of a letter.
message – the text of a letter itself.
add_headers – other parameters of letter’s heading (optional parameter).
We’ll write following code at the end of file email.php
<?php
$subj = "Information request ";
$text = "Dear ".$_POST['name']."!
Thank you for your interest!
You are interested in ".$_POST['preference']."
They are sent for free.
Address to the nearest branch of our office and get a box of this good.";
mail($_POST['email'], $subj, $text);
$subj = "A request for information is obtained";
$text = $_POST['name']." were interested in ".$_POST['preference']." email-address: ".
$_POST['email'];
mail($adminaddress, $subj, $text);
?>
Now a user will get a letter with more detailed information about our goods. The site administrator will also get such letter.
When many people will be interested in our goods we’ll want to systemize information about them somehow and save it in the data base. This will be treated in the following example.
Working with MySQL (saving data in the data base)
First we create a data base and a table. We enter MySQL and accomplish commands:
>CREATE DATABASE products;
>CREATE TABLE clients (name VARCHAR(25), email VARCHAR(25), choise VARCHAR(8));
For communication with MySQL from PHP following functions will be needed:
int mysql_connect(string hostname, string username, string password);
Create connection with MySQL.
Parameters:
Hostname – name of the host on which the data base is placed.
Username – name of a user.
Password – user’s password.
Function returns parameter of int-type which is more than 0 if the connection has been accomplished successfully and is equal to 0 otherwise.
int mysql_select_db(string database_name, int link_identifier);
Select a data base for the work.
Parameters:
Database_name – name of the data base.
link_identifier – ID connection which has been obtained within function mysql_connect. (This parameter is optional; if it isn’t indicated, ID from the last call mysql_connect is used).
The function returns meaning true or false
int mysql_query(string query, int link_identifier);
Function accomplishes request to the data base.
Parameters:
Query – string containing request
link_identifier – look the previous function.
The function returns ID of the result or 0 in case an error occurred.
int mysql_close(int link_identifier);
The function closes connection with MySQL.
Parameters:
link_identifier – look above.
The function returns meaning true or false.
Now our file email.php will look like this:
<?
/* This script gets variables from request.html */
/* Variables for connection with data base */
$hostname = "localhost";
$username = "myusername";
$password = "mypassword";
$dbName = "products";
/* MySQL table within which the data is saved */
$userstable = "clients";
/* email of an administrator */
$adminaddress = "administration@me.com";
/* create a connection */
mysql_connect($hostname,$username,$password) OR DIE("Cannot create a connection");
/* select a data base. If an error occurs – put it out */
mysql_select_db($dbName) or die(mysql_error());
echo "<CENTER>";
echo "Hallo, ".$_POST['name'];
echo "<BR><BR>";
echo "Thanks for your interest. <BR><BR>";
echo "You are interested in ".$_POST['preference'].". Information about them will be sent to you on e-mail: ".
$_POST['email'];
echo "</CENTER>";
/* Send e-mails */
$subj = "Request for information ";
$text = "Dear ".$_POST['name']."!
Thank you for your interest!
You are interested in ".$_POST['preference']."
We send them for free.
Address our nearest branch and get a box of this product.";
mail($_POST['email'], $subj, $text);
$subj="A request for information is obtained ";
$text = $_POST['name']." were interested in ".$_POST['preference']." email-address: ".
$_POST['email'];
mail($adminaddress, $subj, $text);
/* set up a request for insertion of information about customer into the table */
$query = "INSERT INTO $userstable VALUES('$name','$email', '$preference')";
/* Accomplish a request. If an error occurs – put it out. */
mysql_query($query) or die(mysql_error());
echo "Information about you is saved in the data base.";
/* Shut down the connection */
mysql_close();
?>
So easy you can work with data base in PHP. Now beside written notifications information about customer and his interests will be save in MySQL-table.
Working with MySQL (obtaining data from data base).
After saving data we will be interested sometimes in question who of our customers is interested in such a good as ‘Apples’ (don’t mix it with Apple Macintosh).
We’ll write script apple.php
<?
/* The script shows up those customers who like apples more than oranges */
/* Variables for connection with data base*/
$hostname = "localhost";
$username = "myusername";
$password = "mypassword";
$dbName = "products";
/* MySQL table in which data are saved */
$userstable = "clients";
/* create a connection */
mysql_connect($hostname,$username,$password) OR DIE("Cannot create a connection ");
/* select a data base. If an error occurs – put it out */
mysql_select_db($dbName) or die(mysql_error());
/* set up a request which selects all the apple-customers */
$query = "SELECT * FROM $userstable WHERE choise = 'Apples '";
/* Accomplish the request. If an error occurs – put it out. */
$res = mysql_query($query) or die(mysql_error());
/* How many such customers are found */
$number = mysql_num_rows($res);
/* Type all of them accurately */
if ($number == 0) {
echo "<CENTER><P>No apple lovers </CENTER>";
} else {
echo "<CENTER><P>Number of apple lovers: $number<BR><BR>";
/* Get strings one-by-one from the table into massive $row until there are no strings any more*/
while ($row=mysql_fetch_array($res)) {
echo "Customer ".$row['name']." likes Apples.<BR>";
echo "His Email: ".$row['email'];
echo "<BR><BR>";
}
echo "</CENTER>";
}
?>
That’s all, commercial product is nearly ready.



