Introduction to PHP sessions and MySQL documentations

March 12, 2008 by Corina

While getting a more proficient understanding of how PHP works, you will find out that one of the nifty things it can accomplish is talking to a MySQL database server, another is using sessions. Sessions are useful when we want to keep track of users as they browse through a site. As an example for using sessions, we can make sure that only those users who have a valid username and password can gain access to a specific part of a site (something like a membership card), or as another example, in the case of any online store, sessions can help you keep track of what is in the shopping cart at any given time.

Before any other further explications, I’ll emphasize one of the session particularities that I have learned the hard way. It’s important that you start the session before you have any kind of html output since it uses http headers and you can use session variables everywhere in php/html code AFTER you have started the session.
So, as far as I understood, one of the main reasons for using session variables is because A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. To fix this problem, you use sessions so that you can store user information on the server for later use. However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions. If you require a more permanent storage you will need to find another solution, like a MySQL database.

Before you can store any information in your session variable, it is necessary for you to start the session at the very beginning. The function you use is session_start().

When you want to store user data in a session use the $_SESSION predefined variable. This is where you both store and retrieve session data. It would also be a good idea to use the isset() function in association with the $_SESSION variable to check weather there is any content in it, because the reason you use sessions is probably because you want to refer to their content in the near future.

Another thing you have to make sure about sessions is closing them. The functions that accomplish the task are unset() and for permanent close you can use destroy_session(). Here is a short example:

<?php
session_start ( );
if ( isset ( $_SESSION[’ID’] ) ) unset( $_SESSION[’ID’] );
?>

Of course PHP sessions are not of much use without proper storing data containers, so I think that a good way to pair up these things is to introduce a database in the discussion. PHP has a whole array of functions that inquire a database and help you access data. So, next I’ll point out some functions that I found useful in dealing with MySql from the PHP environment.

Of course, all the functions will come in handy if you already have a functional database, and for the sake of exercise, at the beginning it will be a good idea to create one on localhost, so that you can practice.

The way you get there is easy: first of all start the EasyPHP and click on the left upper button with the EasyPHP pictogram, then Configuration and PHPMyAdmin. The same result can be obtained by pressing Ctrl+Y or directly accessing http://127.0.0.1/mysql/. There you can create your database with various tables and through dialog boxes you can interactively describe all your fields, set the constraints, assign primary keys and so on. For populating the tables in your database you have the Insert button so that you can introduce rows in the table. Of course, this can also be accomplished in a different manner. For the users that are aware of the SQL commands, you are provided with an editor so that you can write your script there. Anyway, one way or another, you should be set with a table so that you can inquire and retrieve information from it, even from the PHP script.

And now for the functions: mysql_query() should prove of great use. It allows you to introduce between the brackets any kind of query that will affect the database. Another important problem is that the return from a query can only be in the number of a single row, any other type of returned result will mean an error. In order for us to count the number of rows, we have mysql_num_rows() that retrieves the number. mysql_real_escape_string() escapes special characters in a string for use in a SQL statement, so you might need it for formating the values you want to transmit to the database. mysql_fetch_array() fetches a result row as an associative array, a numeric array, or both. These are all functions I came across in working with the database from the PHP script, but as a good reference,for any further ones that you might need, http://www.php.net is always a good place for searching.

Just to get a general idea, I imagined a situation in which a user has a login form to fill in so that he can gain access to a further page in which, in this case I printed the informations about him that I have in the database.

Here is part of the script, so that the description that i wrote earlier can be more clear:
session_start ( );
include ( ‘connect.php’ );
if ( isset ( $_POST[’submit’] ) ) {
     $username = $_POST[’username’];
     $password = $_POST[’password’];
     $query = sprintf ( “SELECT nr_crt FROM utilizatori WHERE user = ‘%s’ AND pwd = ‘%s’ LIMIT 1;”, 
                     mysql_real_escape_string ( $username ), mysql_real_escape_string ( $password ) );
     $rez = mysql_query ( $query ) or die ( mysql_error ( ) );
     if ( 1 != mysql_num_rows ( $rez ) ) header ( ‘Location: ix.php?msg=login_failed’ );
     else {
          $row = mysql_fetch_assoc($rez);
          $_SESSION[’nr_crt’] = $row[’nr_crt’];
          header(’Location: users.php’);
     }
}
?>

connect.php is a separate script in which we connect to the database on localhost. Then, with the help of the $_POST variable we retrieve the username and password that were provided in the form that is present in the ix.php (an index file). Of course, as I wrote earlier, it is advisable to check first of all with the isset() function, so that we skip some errors in case the information we are trying to retrieve is not to be found. The next step, after we retrieved the username and password (which of course are values from the fields in our database), si to build our query. We obtain in the $rez variable the result from the selection query on the database. If more then one row was selected, we send a login_failed message to the index, so as we can eventually try again. Else, if everything is ok, we store in the session variable(since it is an array we have to use a proper key) the result of the query for further use, moving on to the page accessible to the logged in members.

I hope that this little example will be eloquent enough as to give you an insight of the way that I understood PHP sessions and MySQL database, and of course, be of further use for any of you!

Good luck!

You must be logged in to post a comment.