Internet, webmail, website and Php y Mysql. 

Posted on June   14th, 2009 by Technology Department 

 

Webmail:

Webmail ( Web-based e-mail)  such as Gmail, Yahoo Mail or  Hotmail,  is an e-mail service intended to be primarily accessed via a web browser.

A major advantage of web-based e-mail over application-based e-mail is that a user has the ability to access their inbox from any Internet-connected computer around the world.
Exercise: Create a webmail email account and send a simple message with a attached file to your partner.

Php and html page. The Basics

Php is a programming language which is run by the machine where it is housed, i.e. when a page that has a php code uploads in your navigator, part of the code can be run on the machine where it is housed (where the page comes from) and return information which is different to what is written in the code.
Let's look at an example.
If we write the famous phrase “Hello World” in html code the only thing that will appear will be this simple phrase and only once. If we want it to appear 5 times, we have to write it 5 times and it's the same for anything else we want to do.
In the case of php, if we want to write “Hello World” then there is a sentence for it but if we want it to appear 5000 times on the screen we install a counter (which isn't visible on the page and that runs on the server where the page is housed) When the sentence is printed on the page the counter goes up one unit, checks if the counter has gone up to 5000 and, if this isn't the case, prints the sentence again.
We can appreciate a big difference, or in other words “We can count on functions that help us to make web pages.”
PHP is continually evolving and there are already several version, each one adding new functions to the last.
The aim of this unit isn't to become an expert in php but to learn about some of the tasks that can be performed. For this purpose we are going to apply it to a sales portal in our area La Serena and Don Benito; a type of local Second Hand shop.

What is Mysql?

Mysql is a type of database manager, responsible for managing the data stored in a database which is to be shown on the web page.
The basic idea is the following - we create a database that, in its turn, contains a table and this table contains various records. The most appropriate comparison would be to an archive.
Let's suppose that in this archive we have stored information about all the groups in the school. In this case, 3ºA would be in this archive and would be a table full of data, the same for 3ºB etc.
Each table (group) contains a series of students (identifier) and each student has a number of pieces of personal information, like his name, surnames, street address, telephone, etc. These are stored in records.
In other words, we have database > table > records

1st Create a database

The first thing we're going to do is create our database, whose job is to store all the data about the users. In order to create something, we must first enter into the system, that is, into the database.
We must create an archive with the information pertinent to the connection which we will call config.php. This archive will contain the following information.
a) The address where the database is to be found. In other words, where I'm going to connect to the database. This piece of data is usually an IP address where the database is found or, if it's in the same server, the localhost word.
b) The name of the database.
c) A username to be able to enter into the database Databases contain confidential information and we have to protect them with usernames and passwords.
d) The password needed to enter the database
This file is expressed as follows:

<?php
$db_host = "192.125.0.123";$db_user = "user";$db_pass = "mypassword";$db_name = "secondhand";$db_table = "board";
?>

The first thing to appear is the <?php sign. This indicates that the page is going to work with php and so the server requires the php language to function for the requests that the page will make.

Secondly we find sentences like $nombre = "dato"; Let's see what this sign means. Let's start with the dollar sign, that could have been a euro sign (€) except that the Americans got there before us. When we have a word with $ infront it means that we are generating a variable and assigning it a specific piece of data. In this case, because the piece of data will always be the same because we're not going to change the connection information for the database, we have to write in some speech marks, indicating that:
$db_host = "192.125.0.123";
Note that it finishes with the ;. This tells us that the instruction has finished.
Let's move on to the next value, for this we are going to need the datum username: $db_user = "user";

We can see that you do it in the same way, that is, you give the variable db_user the value that we have been assigned in the database. If your database has a username called Manolo then it would be $db_user = "manolo". You do it in the same way for the following two variables.
The last datum refers to the chosen table. You have to remember that once the connection to the database is realised, we have to take the data from a table. In this case we call it a board.
To finish this file we have to show that the php is has finished, so we put ?>.

Creating a table in a database

Once we have the database with the information about where it is, what it's called, the username and password, we must create a table to store the data of the users. We must show the php code again. 1st - enter in the database, 2nd create a table, 3rd create records in the table. The code, that will form part of the file install.php, is:

<?php

// Incluimos el codigo anterior

include ("config.php");

mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db($db_name );
mysql_query("CREATE TABLE `$db_table` (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id) ,
field_1 TEXT ,
field_2 TEXT ,
field_3 TEXT ,
field_4 TEXT ,
field_5 TEXT ,
field_6 TEXT ,
field_7 TEXT ,
field_8 TEXT ,
field_9 TEXT )") or die("Error! Table not be created.");

echo "Table created. ";  ?>

 

We're going to see what this piece of code does. The first thing is the instruction 'include' that, as the word implies, includes the code config.php in this file because the data it contains is going to prove necessary.

It's a good idea to use this sentence because it saves us work and orders the code.
we have to note, without respect to the order, that when the codes are very long it is convenient to use the symbol // to make comments. In this way that which appears after the // isn't valid for php and it allows us to be a bit clearer in the code that we write or that another programmer has written.
mysql_connect (base, username, password) -> This php instruction connects with the name database which has a username and password. In this case, this data is taken from the information in the file config.php
Once we have connected with the database, we have to choose a specific database because our server can contain several databases. To do this we use mysql_select_db($db_name ). $db_name will be replaced by the value that it has in the file config.php. Now we have the connection with the database. Now it's time to create the table and to do this we use this instruction.
mysql_query ( "create table" `$db_table ` (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id) ,
field_1 TEXT ,
field_2 TEXT , etc etc
mysqql_query Consults the database which, in this case, is an order, that of creating the table. {"create table" } with the name {$db_table} , which, in our case, will be board and will appear with the characteristics seen in brackets id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id). With respect to this last one, what it shows is that the identifier of each record has to be an integer, that is a whole number, that it shouldn't be nil, so that it can be differentiated from other records, that each time a record is added the number grows and that the main keyword needed for access is going to be this id identifier. So each new advert is going to have an identifier or identity number. For example, advert 36, that refers to the sale of a mobile phone, could have an id of 55 and identifies it from among the other adverts and its fields, like the price, name of owner etc, will be referred to this id.
Lastly we can see the fields that it should contain. In this case, we're going to call them field_1, field_2 ... specifying that they are text fields. We can also name them telephone, name, surname, price...
At the end of the mysql_query sentence it says die. This means that if this doesn't produce the creation the table, then it should abandon the task.
The last instruction says: echo "Table created. ";. This means that the phrase Table created will be written on the screen

Form used for data entry

 

To enter the data in the database we first have to have a form and then this will send the data to another file that will manage the data so that it can be incorporated in the database.
The form, written in html, looks something like this:

 

<form enctype='multipart/form-data' action='process.php' method='POST'>
 <div align="center">
 <table border="1" cellspacing="1" style="border-collapse: collapse" width="743" cellpadding="5" height="371">
 <tr><td height="22" width="45" bordercolor="#FFFFFF">
 <img src="../../../image/obj_bbs.gif" width="45" height="45"></td>
 <td height="22" width="72" bordercolor="#FFFFFF">
 <font face="Verdana" size="2">Name</font></td>
 <td height="22" width="617" bordercolor="#FFFFFF">
 <font face="Verdana"><input type=text name='nombre' size=25>*</td></tr><tr>

 

 

 

 

<?php
include("global.inc.php");
$errors=0;
$error="Los siguientes errores ocurrieron...The following errors occured while processing your form input.<ul>";
pt_register('POST','telephone');
pt_register('POST','nombre');
pt_register('POST','email');
pt_register('POST','apellidos');
pt_register('POST','message');
pt_register('POST','object');
pt_register('POST','password');
pt_register('POST','image');
pt_register('POST','title');
pt_register('POST','prices');

 

if($nombre=="" || $email=="" || $apellidos=="" || $message=="" ){
$errors=1;
$error.="<li>No completo todo el formulario. Por favor vuelva a rellenar todos los campos....You did not enter one or more of the required fields. Please go back and try again.";
}
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."@"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email)){
$error.="<li> Formato de Correo no valido.....Invalid email address entered";
$errors=1;
}
if($errors==1) echo $error;
else{
include ("photo-validate.php");
include ("create.php");

$today = date("F j, Y, g:i");
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);

$query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9, field_10, field_11) VALUES ('" . $_POST['nombre'] . "','" . $_POST['apellidos'] . "','" . $_POST['email'] . "','" . $_POST['password'] . "','" . $_POST['telephone'] . "','" . $_POST['object'] . "','" . $_POST['message']. "','" . $_POST['title'] . "','photos/".$file_name."','" . $today . "','" . $_POST['prices'] . "')";
mysql_query($query);
mysql_close($link);

}
?>
<html><head><title> Gestion de anuncio </title></head><body>
<p align="center"><b>
<A HREF="javascript:history.back()"> <font color="#000080" size="4">Volver Atrás
</font> </A>
</b>
</body></html>


It's worth paying attention to the label “form” that starts the form and that will, furthermore, appear again at the end of the form that isn't written here so as not to make the code overly long. After form we see the way we are going to manage the data and then what we are going to do with this data (action), which, in this case, shows that it is sent to the file process.php through the post method (there's another method called Get) The rest of the code refers to the width of the fields, the colour of the border, the type of border etc. In the second to last line we can see input type = text name = nombre. This tells us that the first field to be completed is a text field and that it is called nombre. We can download the full code once we have seen this script.

File to enter the data in the database

 

 We have an archive called process.php that's going to take on the job of introducing the data into the database. Let's see what there is inside it.

 

<?php
include("global.inc.php");
$errors=0;
$error="The following errors occurred while processing your form input.<ul>";
pt_register('POST','telephone');
pt_register('POST','nombre');
pt_register('POST','email');
pt_register('POST','apellidos');
pt_register('POST','message');
pt_register('POST','object');
pt_register('POST','password');
pt_register('POST','image');
pt_register('POST','title');
pt_register('POST','prices');

 

if($nombre=="" || $email=="" || $apellidos=="" || $message=="" ){
$errors=1;
$error.="<li>You did not enter one or more of the required fields. Please go back and try again.";
}
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."@"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email)){
$error.="<li> Invalid email address entered";
$errors=1;
}
if($errors==1) echo $error;
else{
include ("photo-validate.php");
include ("create.php");

$today = date("F j, Y, g:i");
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);

$query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9, field_10, field_11) VALUES ('" . $_POST['nombre'] . "','" . $_POST['apellidos'] . "','" . $_POST['email'] . "','" . $_POST['password'] . "','" . $_POST['telephone'] . "','" . $_POST['object'] . "','" . $_POST['message']. "','" . $_POST['title'] . "','photos/".$file_name."','" . $today . "','" . $_POST['prices'] . "')";
mysql_query($query);
mysql_close($link);

}
?>
<html><head><title> Advertise admin </title></head><body>
<p align="center"><b>
<A HREF="javascript:history.back()"> <font color="#000080" size="4">Volver Atrás
</font> </A>
</b>
</body></html>

Gestion de anuncio

The line include("global.inc.php") indicates that the file global.inc is coming into play to add a function that creates the variables of the fields on the form, i.e., if we enter a field with the name 'lugar' then through this file and a function that it contains (that we're not going to look at) the variable "$lugar" is generated.

For simplicity's sake we are not going to look at this file because, like others, it isn't essential to this topic. Let's look at the following lines

 if($nombre=="" || $email=="" || $apellidos=="" || $message=="" ){ $errors=1;

In this case, it doesn't say ->if ( condicion) then {tarea}. The function 'if' looks at what there is inside the brackets and if this has been done then it runs what we see between the braces {}.

 It this case it checks if the mail address, the surname field or the name field are empty. If this is the case it puts $errors=1; and it also assigns the text

You did not enter one or more of the required fields. Please go back and try again

 A little later it does another check to see if the email field is missing the @ or if it contains any other type of error (we won't see this function). Then, if this happens, another text ->

Invalid email address to the variable $error and then it checks if any error was made in these cases ( if($errors==1) echo $error;. I.e. if you fill in the form incorrectly the error is printed the error on the screen.

 If everything is ok then you go on to 'else' and it runs what comes next, in this case it includes two new files photo-validate and create.php The first file is going to check if the type of photo file is valid and the second is going to generate miniatures of the photos sent in.

 Let's see the next chunk of code

 1º $today = date("F j, Y, g:i");

2º include("config.inc.php");

3º $link = mysql_connect($db_host,$db_user,$db_pass);

 4º if(!$link) die ('Could not connect to database: '.mysql_error());

5º mysql_select_db($db_name,$link);

 The first line generates the variable $today that allows us to know the date and time. We see that it is done in the same way as the reserved function 'date' with some parameters in brackets which indicate how the time should be shown. A reserved function is a function specific to php, stored in its own system that runs itself, in other words, “you don't have to tell the system what to do because php already knows”.

 There are many ways to show the date and you can look at the php manual to see the different options.

The second line calls config.inc.php, the file that contains the data from the database. It is called up because we are soon going to enter data in the records of the table. The third generates the variable $link that contains the data needed to connect to the database. It contains the instruction mysql_connect for the connection.

The fourth checks if the connection has been successful. It says if(!$link) die. this means that if what is inside the brackets isn't done (for this reason we add the !symbol at the start of the variable) then the programmes stops running and a message appears on the screen that says No ha podido establecer conexión con la base de datos

The fifth selects the database once you are connected. $db_name is the name of the database.

The next thing is to create a variable that is going to contain the consultation. In this case it is the following

 $query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9, field_10, field_11) VALUES ('" . $_POST['nombre'] . "','" . $_POST['apellidos'] . "','" . $_POST['email'] . "','" . $_POST['password'] . "','" . $_POST['telephone'] . "','" . $_POST['object'] . "','" . $_POST['message']. "','" . $_POST['title'] . "','photos/".$file_name."','" . $today . "','" . $_POST['prices'] . "')";

 

I.e. insert into ( insert into ) the table ($db_table) dta in the records field_1, field_2 ...... taken from the form with value valor $_POST['nombre'] ., $_POST['apellidos] ., $_POST['email'] .....

Everything is logical but we must take care to respect the way in which we enter the data, paying attention to the speech marks, brackets, etc. This sentence can be modified with whatever values you want but you have to use the words 'insert into' to be able to enter the data.

Then we have mysql_query($query); which consults the database and mysql_close($link); that closes the connection to the database.

Eureka, now we have our first record stored in the database!

The last thing we must do is shut the php and open the html code to insert a javascript that allows us to return to the page before.

Dictionary:

More information 

Most common problems with redirection headers ( Cannot modify header information - headers already sent by) These types of errors appear in surprising way and apparently fulfilling all the criteria. They usually appear in the sentence header("Location: otra-pagina.php"); First, Of there is a blank space after the session closer ?> it causes an error. Make sure that the last line of the php code is ?> Second, don't put echo before the sentence Third, don't but a html label before or after the php code Other applications in php and Mysql First - photograph loader (files) with html, php and Mysql forms

 

Posted on 2009