Introduction to PHP, MySQL
and AJAX
PHP
PHP is a powerful tool for making dynamic and interactive
Web pages.
PHP stands for PHP: Hypertext Preprocessor
It is server side scripting Language.
It runs on apache server.
PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
PHP is an open source software
PHP - What is it / does it do?
Web Page Request Load PHP File
PHP Engine –
Run Script
HTML Response
Web Server PHP Results
User
PHP
PHP is similar to C
All scripts start with <?php and with with ?>
Line separator: ; (semi-colon)
Code block: { //code here } (brace brackets)
White space is generally ignored (not in strings)
Comments are created using:
// single line quote
/* Multiple line block quote */
Precedence
Enforced using parentheses
E.g. $sum = 5 + 3 * 6; // would equal 23
$sum = (5 + 3) * 6; // would equal 48
Variables in PHP
A variable is defined with a $ Sign in PHP.
$var_name = value;
A variable name must start with a letter or an underscore
"_“.
A variable name can only contain alpha-numeric characters
and underscores (a-z, A-Z, 0-9, and _ )
A variable name should not contain spaces. If a variable
name is more than one word, it should be separated with an
underscore ($my_string), or with capitalization
($myString).
PHP - Constants
Constants are special variables that cannot be
changed
Use them for named items that will not change
Created using a define function
define(„milestone‟, 1.6);
Used without $
$km = 5 * milestone;
Example
Create a constant with a case-sensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Create a constant with a case-insensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Datatypes in PHP
PHP supports the following data types:
String
Integer
Float (floating point numbers)
Boolean
Array
Object
NULL
PHP Forms
What is Form?
When you login into a website or into your mail box, you are interacting
with a form.
Forms are used to get input from the user and submit it to the web
server for processing.
The diagram below illustrates the form handling process.
The code below creates a simple registration form
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Registration Form</h2>
<form action="registration_form.php" method="POST"> First name:
<input type="text" name="firstname"> <br> Last name:
<input type="text" name="lastname">
<input type="hidden" name="form_submitted" value="1" />
<input type="submit" value="Submit">
</form>
</body>
</html>
Submitting the form data to the server
PHP POST method
This is the built in PHP super global array variable that is used to get
values submitted via HTTP POST method.
The array variable can be accessed from any script in the program; it
has a global scope.
This method is ideal when you do not want to display the form post
values in the URL.
A good example of using post method is when submitting login details
to the server.
Cont..
<?php
$_POST['variable_name'];
?>
“$_POST[…]” is the PHP array
“'variable_name'” is the URL variable name.
Cont..
PHP GET method
This is the built in PHP super global array variable that is
used to get values submitted via HTTP GET method.
The array variable can be accessed from any script in the
program; it has a global scope.
This method displays the form values in the URL.
It‟s ideal for search engine forms as it allows the users to
book mark the results.
<?php
$_GET['variable_name'];
?>
“$_GET[…]” is the PHP array
“'variable_name'” is the URL variable name.
PHP - Validate Name
The code below shows a simple way to check if the
name field only contains letters and whitespace. If
the value of the name field is not valid, then store an
error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
PHP - Validate E-mail
The easiest and safest way to check whether an email
address is well-formed is to use PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed,
then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP Arrays
An array stores multiple values in one single
variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than
one value at a time.
If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
Create an Array in PHP
In PHP, the array() function is used to create an
array:
array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one
or more arrays
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle
Corporation
MySQL is named after co-founder Monty Widenius's
daughter: My
The data in a MySQL database are stored in tables. A table
is a collection of related data, and it consists of columns and
rows.
Databases are useful for storing information categorically.
A company may have a database with the following tables:
Employees
Products
Customers
Orders
Database Queries
A query is a question or a request.
We can query a database for specific information and have
a recordset returned.
Look at the following query (using standard SQL):
SELECT LastName FROM Employees
The query above selects all the data in the "LastName"
column from the "Employees" table.
PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to
connect to the server:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Close the Connection
The connection will be closed automatically when the script
ends. To close the connection before, use the following:
mysqli_close($conn);
The PHP functions for use with MySQL have the following
general format −
mysql_function(value,value,...);
The second part of the function name is specific to the
function, usually a word that describes what the function
does.
mysqli_connect($connect); mysqli_query($connect,"SQL
statement");
MySQL Connection Using PHP Script
PHP provides mysql_connect() function to open a database
connection. This function takes five parameters and returns a MySQL
link identifier on success or FALSE on failure.
Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);
server
Optional − The host name running the database server. If not specified,
then the default value will be localhost:3306.
user
Optional − The username accessing the database. If not specified, then
the default will be the name of the user that owns the server process.
passwd
Optional − The password of the user accessing the database. If not
specified, then the default will be an empty password.
new_link
Optional − If a second call is made to mysql_connect() with the same
arguments, no new connection will be established; instead, the
identifier of the already opened connection will be returned.
client_flags
Optional − A combination of the following constants −
MYSQL_CLIENT_SSL − Use SSL encryption.
MYSQL_CLIENT_COMPRESS − Use compression protocol.
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function
names.
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds
of inactivity before closing the connection.
Create a Database using PHP Script
PHP uses mysql_query function to create or delete
a MySQL database. This function takes two
parameters and returns TRUE on success or FALSE
on failure.
mysql_query( sql, connection );
sql
Required - SQL query to create or delete a MySQL
database
connection
Optional - if not specified, then the last opened
connection by mysql_connect will be used.
Drop Database using PHP Script
PHP uses mysql_query function to create or delete a MySQL
database. This function takes two parameters and returns TRUE on
success or FALSE on failure.
Syntax
bool mysql_query( sql, connection );
sql
Required − SQL query to create or delete a MySQL database
connection
Optional − if not specified, then the last opened connection by
mysql_connect will be used.
AJAX Introduction
AJAX is a developer's dream, because you can:
Read data from a web server - after the page has
loaded
Update a web page without reloading the page
Send data to a web server - in the background
What is AJAX?
AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language.
AJAX just uses a combination of:
A browser built-in XMLHttpRequest object (to
request data from a web server)
JavaScript and HTML DOM (to display or use the
data)
AJAX allows web pages to be updated
asynchronously by exchanging data with a web
server behind the scenes.
This means that it is possible to update parts of a
web page, without reloading the whole page.
1. An event occurs in a web page (the page is loaded, a
button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web
server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by
JavaScript
AJAX - The XMLHttpRequest Object
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes.
This means that it is possible to update parts of a web page, without
reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox, IE7+, Edge, Safari,
Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Older Browsers (IE5 and IE6)
Old versions of Internet Explorer (5/6) use an ActiveX
object instead of the XMLHttpRequest object:
variable = new ActiveXObject("Microsoft.XMLHTTP");
To handle IE5 and IE6, check if the browser supports
the XMLHttpRequest object, or else create
an ActiveX object:
Example
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
The url - A File On a Server
The url parameter of the open() method, is an address to a file on a
server:
xhttp.open("GET", "ajax_test.asp", true);
The file can be any kind of file, like .txt and .xml, or server scripting
files like .asp and .php (which can perform actions on the server before
sending the response back).
The onreadystatechange Property
The readyState property holds the status of the
XMLHttpRequest.
The onreadystatechange property defines a function to be
executed when the readyState changes.
The status property and the statusText property holds the
status of the XMLHttpRequest object.
Property Description
onreadystatec Defines a function to be called when the readyState property
hange changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
403: "Forbidden"
404: "Page not found"
AJAX - Send a Request To a Server
The XMLHttpRequest object is used to exchange data with
a server.
Send a Request To a Server
To send a request to a server, we use the open() and send()
methods of the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
open(method, url, Specifies the type of request
async)
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no size
limitations).
Sending user input (which can contain unknown characters), POST is
more robust and secure than GET.
GET Requests
A simple GET request:
Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
POST Requests
A simple POST request:
Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
Synchronous Request
To execute a synchronous request, change the third
parameter in the open() method to false:
xhttp.open("GET", "ajax_info.txt", false);
Sometimes async = false are used for quick testing. You will
also find synchronous requests in older JavaScript code.
Since the code will wait for server completion, there is no
need for an onreadystatechange function:
Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;