Lecture 7 - PHP and MySQL
Lecture 7 - PHP and MySQL
2
Sessions
Setting Session variables is simple
Imagine we have received $name via a HTML form
We can store this information for use in other pages
It is essential that if we are using sessions, the first
thing we do is call:
session_start()
<?php
session_start();
extract($_POST);
$_SESSION[‘name’] = $name;
?>
3
Sessions
Now, on another page we can see if a session exists
If one does then we can welcome the visitor
<?php
session_start();
if($_SESSION[‘name’]){
print “Hi”.$_SESSION[‘name’].“. A session is
registered”;
}else{
print “There is no session registered…”;
}
?>
• The condition for the ‘if’ statement is true if the session
variable name exists.
• If it isn’t then we can take another course of action.
4
Sessions
Sessions end when a user closes a browser.
We can also terminate sessions to facilitate a logout
by a user.
Note that even though we are destroying this session,
we still have to call session_start() first.
<?php
session_start();
session_destroy();
?>
5
Redirecting a Browser
We can use the header() function to redirect a browser to a
different page.
For example, to redirect a browser to a page called login.php
we would use
header('Location: login.php');
This function is useful for returning a user to a login page if e.g.
6
Architecture
Request Page Read File
Web Browser Web Server Page with
PHP
Send code
HTML page
Pass PHP page
and server variables
Generate
HTML (GET
page attributes, Server settings, etc.)
PHP
Interpreter
Interact with MySQL
Database
MySQL
Limittations of MySQL
programmatically
Does not support nested selections. There are ways to overcome
users.
During development, you would use it for testing queries
database from the user. Make sure that the data will
not break your SQL queries.
mysql_real_escape_string(): a useful function for