Chapter1:-Server Side Scripting Basics in PHP
Chapter1:-Server Side Scripting Basics in PHP
Server-side scripting is a web server technology in which a user's request is fulfilled by running a script
directly on the web server to generate dynamic web pages. It is usually used to provide interactive web
sites that interface to databases or other data stores. This is different from client-side scripting where
scripts are run by the viewing web browser.
The primary advantage to server-side scripting is the ability to highly customize the response based on the
user's requirements, access rights, or queries into data stores. From security point of view, server-side
scripts are never visible to the browser as these scripts are executes on the server and emit HTML
corresponding to user's input to the page.
In contrast, server-side scripts, written in languages such as PHP, ASP.NET, Java, ColdFusion, Perl,
Ruby, Go, Python, and server-side JavaScript, are executed by the web server when the user requests a
document. They produce output in a format understandable by web browsers (usually HTML), which is
then sent to the user's computer. The user cannot see the script's source code (unless the author publishes
the code separately), and may not even be aware that a script was executed. Documents produced by
server-side scripts may, in turn, contain client-side scripts.
Server-side Web scripting is mostly about connecting Web sites to back end servers, such as databases.
This enables two-way communication:
Server-side scripting is about "programming" the behavior of the server while client-side scripting is
about "programming" the behavior of the browser. Normally, when a browser requests an HTML file, the
server returns the file. However, if the file contains a server-side script, the script is executed on the
server before the file is returned to the browser as plain HTML.
In server side script, since the scripts are executed on the server, the browser that displays the file does
not need to support scripting at all. The followings are server-side scripts:
PHP (*.php)
Active Server Pages (ASP)
ANSI C scripts Java via JavaServer Pages (*.jsp)
JavaScript using Server-side JavaScript (*.ssjs)
Lasso (*.lasso) etc
The main focus here is PHP, which is a server-side scripting language, which can be embedded in HTML
or used as a standalone binary, and could be run with open source software like WAMP server.
PHP can dynamically create the HTML code that generates the Web page.
Web page visitors see the output from scripts, but not the scripts themselves.
PHP is a server-side scripting language, which means that the scripts are executed on the server, the
computer where the Web site is located. This is different than JavaScript, another popular language for
dynamic Web sites. JavaScript is executed by the browser, on the user‘s computer. Thus, JavaScript is a
client-side language.
Because PHP scripts execute on the server, PHP can dynamically create the HTML code that generates
the Web page, which allows individual users to see customized Web pages. Web page visitors see the
output from scripts, but not the scripts themselves.
PHP is particularly strong in its ability to interact with databases. PHP handles connecting to the database
and communicating with it, so we don‘t need to know the technical details for connecting to a database or
for exchanging messages with it, it is enough telling PHP the name of the database and where it is, and
PHP handles the details. It connects to the database, passes our instructions to the database, and returns
the database response to us.
dBASE ,Informix ,Ingres, Microsoft SQL Server ,mSQL ,MySQL ,Oracle ,PostgreSQL,Sybase
and etc.
Hence, PHP scripts in the Web site can store data in and retrieve data from any supported database. PHP
also can interact with supported databases outside a Web environment. Database use is one of PHP‘s best
features.
Use of PHP:
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data,
return data to the user.
Using php, it is possible to add, delete, and modify elements within our database.
It helps to assign sessions and cookies for privacy.
Using PHP, we can restrict users to access some pages of the website.
It can encrypt data and so mores
The syntax of PHP is: - There are four ways to write php syntaxes:-
To work with server script, for example with PHP, we need to install a web server, programming itself,
and database server. For PHP, we install PHP as a programming. There are many web servers to choose
for PHP uses; the most commonly used web server is called Apache which we can download from the
internet freely. Similarly, for database, there are many options to use; the most popular database server for
web pages is MySQL which again can be downloaded freely from internet.
PHP is also available freely on the internet. In order to develop and run PHP Web pages three vital
components need to be installed on computer system.
Web Server - PHP will work with virtually all Web Server software, including Microsoft's
Internet Information Server (IIS) but then most often used is freely available Apache Server.
Database - PHP will work with virtually all database software, including Oracle and Sybase but
most commonly used is freely available MySQL database.
PHP Parser - In order to process PHP script instructions a parser must be installed to generate
HTML output that can be sent to the Web Browser.
For the apache code to execute properly, it should be saved in web directory. The web directory depends
on what web server is used. For example, for xampp web server, our web directory can be install in
C:\xampp\htdocs‖. Hence, we should save PHP files in this folder, www.
For XAMPP server, we save the php code in C:\xampp\htdocs\your file here.
A comment is the portion of a program that exists only for the human reader and stripped out before
displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant to the
local code. Here are the examples of single line comments.
<?php
#This is a single line comment and
// This also a single line comments too. Each style comments only print "An example with single
line comments";
?>
Multi-lines comments: They are generally used to provide pseudo code algorithms and more
detailed explanations when necessary. Use /* and */ Here are the example of multi lines
comments.
<?php
/* This is a comment with multiline
………………………………………
………………………………………
…………………………………….
*/
Print "An example with multi line comments";
?>
Output Statements:-
The two most basic constructs for displaying output in PHP are echo and print. Both can be used either
with parentheses or without them.
Echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take
multiple parameters (although such usage is rare) while print can take one argument. echo is marginally
faster than print. The echo or print statement can be used with or without parentheses: echo or echo().
The parameterized version of echo does not accept multiple arguments. The general format of the print
statement is as follows:
print output;
print(output);
The command print is very similar to echo, with two important differences:
A variable is a special container that can be defined to hold a value such as number, string, object, array,
or a Boolean. The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
PHP does a good job of automatically converting types from one to another when
necessary.
For example:-
o $distance = 2;
o $name = ―stay home‖;
As shown above, Numbers are not enclosed in quotes when they are assigned to variable. However,
strings should be enclosed in either single or double quotes (― or ‗). The quotes tell PHP that the
characters are a string, handled by PHP as a unit. Without the quotes, PHP doesn‘t know the characters
are a string and won‘t handle them correctly. PHP has a total of eight data types which we use to
construct our variables:
Strings:
They are sequences of characters, like "PHP supports string operations". Following are valid examples of
string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
echo($literally);
echo($literally);
?>
There are no artificial limits on string length - within the bounds of available memory, we ought to be
able to make arbitrarily long strings. Strings that are delimited by double quotes (as in "this") are
preprocessed in both the following two ways by PHP:
Certain character sequences beginning with backslash (\) are replaced with special characters
Variable names (starting with $) are replaced with string representations of their values.
PHP provides a large number of predefined variables to all scripts. The variables represent everything
from external variables to built-in environment variables, last error messages to last retrieved headers.
Superglobals — Superglobals are built-in variables that are always available in all scopes
$GLOBALS — References all variables available in global scope
$_SERVER — Server and execution environment information
$_GET — HTTP GET variables
$_POST — HTTP POST variables
$_FILES — HTTP File Upload variables
$_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and $_COOKIE
variables
$_SESSION — Session variables
$_COOKIE — HTTP Cookies
$php_errormsg — The previous error message
Many of these variables, however, cannot be fully documented as they are dependent upon which server
are running, the version and setup of the server, and other factors.
Removing Variables
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is declared.
PHP variables can be one of three scope types:
Local variables:- The variable is only accessible from within the function (or method) that created it A
variable declared in a function is considered local; that is, it can be referenced solely in that function. Any
assignment outside of that function will be considered to be an entirely different variable from the one
contained in the function:
<?php
$x = 4;
function assignx () {
$x = 0;
assignx();
?>
o $x inside function is 0.
o $x outside of function is 4.
Global variables:- The variable is accessible from anywhere in the script. Global variable can be
accessed in any part of the program. However, in order to be modified, a global variable must be
explicitly declared to be global in the function in which it is to be modified. This is accomplished,
Stay@Home prepared by Dagne G Page 8
Lecture Note: Advanced internet programming 2012 E.C
conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized
as global. Placing this keyword in front of an already existing variable tells PHP to use the variable
having that name. Consider an example:
<?php
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++ ;
addit();
?>
o Somevar is 16
Static variables:- this type of variables be either a global or local variable. Both are created by preceding
the variable declaration with the keyword static. In contrast to the variables declared as function
parameters, which are destroyed on the function's exit, a static variable will not lose its value when the
function exits and will still hold that value should the function be called again.
<?php
function keep_track() {
STATIC $count = 0;
$count++;
keep_track();
keep_track();
keep_track();
?>
Variable Naming:
b. PHP Constants
A constant is a name or an identifier for a simple value. A constant value cannot change during the
execution of the script. By default a constant is case-sensitive. By convention, constant identifiers are
always uppercase. A constant name starts with a letter or underscore, followed by any number of letters,
numbers, or underscores. If we have defined a constant, it can never be changed or undefined.
To define a constant we have to use define() function and to retrieve the value of a constant. Unlike with
variables, you do not need to have a constant with a $. We can also use the function constant() to read a
constant's value if we wish to obtain the constant's name dynamically.
constant () function is used to return the value of the constant. This is useful when we want to retrieve
value of a constant, but we do not know its name, i.e. It is stored in a variable or returned by a function.
constant () example:
<?php
define("MINSIZE", 50);
echo MINSIZE;
?>
Only scalar data (boolean, integer, float and string) can be contained in constants. PHP provides a large
number of predefined constants to any script which it runs. There are five magical constants that change
depending on where they are used. For example, the value of __LINE__ depends on the line that it's used
on in script.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression,
it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
One especially useful construct is the ternary conditional operator, which plays a role somewhere between
a Boolean operator and a true branching construct. Its job is to take three expressions and use the truth
value of the first expression to decide which of the other two expressions to evaluate and return. The
syntax looks like:
The value of this expression is the result of yes-expression if test-expression is true; otherwise, it is the
same as no-expression. For example, the following expression assigns to $max_num either $first_num or
$second_num, whichever is larger: $max_num = $first_num > $second_num ? $first_num :
$second_num;
Example:-
<?php
$x=2;
$y=10; If $y%$x>3?‖$y value is more than 3 folds of $x‖:‖$y is not large enough‖;
?>
i. String concatenation operation: - To concatenate two string variables together, use the dot (.)
operator like echo $string1 . " " . $string2;
ii. strpos() function:- used to search for a string or character within a string. If a match is found in
the string, this function will return the position of the first match. If no match is found, it will
return FALSE.
Written as strops(orginal string, new string)
Example: the following code used to show from where the word ―world‖ started.
<?php
echo strpos("Hello world!","world");
?>
The output will be 6. As seen the position of the string "world" in our string is position 6. The
reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
iii. The strrev( ) function:- takes a string and returns a reversed copy of it.
Has a syntax:-
$string = strrev(string);
For example:
echo strrev("study hard");
drah yduts
iv. The strlen() function:- is used to find the length of a string. For example:- To find the length of
"Hello world!", we can write as follows
<?ph
echo strlen("Hello world!");
?>
(Reading Assignment)
else
echo "Have a nice day!";
?>
While Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long
as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):
Example
<?php
$x=1;
while($x<=5) {
echo "The number is: $x <br>";
$x++;
}
?>
Do…While Loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x=1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the loop.
This means that the do while loop would execute its statements at least once, even if the condition fails
the first time.
Syntax
Parameters:
Example
<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
}
?>
The for each loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
For every loop iteration, the value of the current array element is assigned to $value and the array pointer
is moved by one, until it reaches the last array element.
Example
<?php
$colors = array("red","green","blue","yellow");
for each ($colors as $value) {
echo "$value <br>";
}
?>
Php Arrays
Example
Stay@Home prepared by Dagne G Page 16
Lecture Note: Advanced internet programming 2012 E.C
<?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.
array();
$cars=array("Volvo","BMW","Toyota");
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) {
echo $cars[$x];
echo "<br>";
}
?>
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The above code‘s action attribute value can be represented as the file names itself like:-
<form action=‖xy.php‖ method=‖Get‖>
The POST method transfers information via HTTPs headers. The information is encoded as described in
case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
Relatively secured and could large data in requesting and responding data
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header is secured enough on HTTP protocol.
The PHP provides $_POST associative array to access all the sent information using POST
method.
Variables sent with HTTP POST are not shown in the URL
The $_POST variable is used to collect values from a form with method="post".
Information sent from a form with the POST method is invisible to others For example
http://localhost/xy.php
The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and $_COOKIE
variables
This variable can be used to get the result from form data sent with both the GET and POST
methods.
Example:- <?php
Where
action=―…‖ is the page that the form should submit its data to, and
method=―…‖ is the method by which the form data is submitted. If the method is
get the data is passed in the url string, if the method is post it is passed as a
separate file.
The form variables are available to PHP in the page to which they have been submitted. The
variables are available in two superglobal arrays created by PHP called $_POST and $_GET.
The basic concept that is important to understand is that any form element will automatically be
available to PHP scripts. See the following example:
When the process is done, if it is done making validations, it will check to see if there is an error message.
If there is, it displays the error message. If there are no errors, it displays a success message.
<Html>
<Body>
<form action="a.php" method="post">
Your Name: <input type="text" name="yourname" /><br />
E-mail: <input type="text" name="email" /><br/>
<p>Do you like this website?
<input type="radio" name="likeit" value="Yes" checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure" /> Not sure</p><br/>
<p>Your comments:<br />
<textarea name="comments" rows="10" cols="40"></textarea></p>
<p><input type="submit" value="Send!"></p>
</form>
</body>
</html>
All variables passed to the current script via the HTTP POST method are stored in associative
array $_POST. For example, in PHP we can access data from each field using $_POST['NAME'],
where NAME is the actual field name.
If we submit the above form, we would have access to a number of $_POST array values inside
the a.php file:
In php, we can check the validity of inputs such as URL, E-mail, digits, letters and other special
characters etc using functions. For example preg_match() function used to match list of inputs with
defined lists. For example, see the following rules:-
i. URL Address:- If there is an input field named "website" we can check for a valid URL address
like this:
$url = htmlspecialchars($_POST['website']);
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i",$url)) {
die("URL address not valid");
}
From the code given above, if the input held by $url is not match with the given string , then the die()
function force the system to terminate the running .
ii. Digits 0-9 only: - This uses to check whether an input is digit/ number or not.
The following is a syntax to check if $age is a number or not. If not number, it display ―Please enter
numbers only for Age‖ .
$age= htmlspecialchars($_POST['age']);
if (!preg_match("/\D/",$age)) {
iii. Validate e-mail address:- Used to check an email is valid, i.e to have valid forms.
There is a simple way to check if data entered into input field named "email" is an e-mail address
without any unnecessary complications and fancy regular expressions.
$email = htmlspecialchars($_POST['email']);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
die("E-mail address not valid");
}
iv. Letters a-z and A-Z only:- This code will check if $text is made of letters a-z and A-Z only (no
spaces, digits or any other characters):
$name = test_input($_POST["name"]);
if (preg_match("/[^a-zA-Z]/",$text)) {
die("Please enter letters a-z and A-Z only!");
}
Please read Lab tutorials more about the forms and form validations.
Once a file is opened using fopen() function it can be read with a function called fread(). This function
requires two arguments. These must be the file pointer and the length of the file expressed in bytes. The
file‘s length can be found using the filesize() function which takes the file name as its argument and
returns the size of the file expressed in bytes.
Open a file using fopen() function. Syntax:- variable= fopen(―text file‖, ―mode‖); where mode
mean r, r+, w, w+ etc as shown in the next page.
Get the file's length using filesize() function. The syntax is filesize($filename );
Read the file's content using fread() function. Has syntax variable = fread( filename, filesize);
Close the file with fclose() function. It uses when finished working with a file stream to save
space in memory.
Syntax:- fclose(file name that contains the opened files);
$handle from the following example.
Example:- Files modes can be specified as one of the six options in this table.
To create a directory in the same directory as your PHP script simply provide the directory name.
To create a new directory in a different directory specify the full path when calling mkdir().
<?php
?>
Deleting a Directory
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
</body></html>
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Syntax
The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
Note: The setcookie() function must appear BEFORE the <html> tag.
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP Session
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
Session variables hold information about one single user, and are available to all pages in one
application.
If you need a permanent storage, you may want to store the data in a database.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any
HTML tags.
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
To remove all global session variables and destroy the session, use session_unset() and session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be
reused on multiple pages. This will help developers to make it easy to change the layout of complete
website with minimal effort. If there is any change required then instead of changing thousand of files just
change included file.
The include() function takes all the text in a specified file and copies it into the file that uses the
include function.
If there is any problem in loading a file then the include() function generates a warning but the
script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php with
the following content.
<a href="http://www.tutorialspoint.com">Home</a>
<a href="http://www.w3schools.com">w3schools</a>
<a href="http://www.ajax.com">AJAX</a>
<a href="http://www.mysql.com">MySQL</a> <br />
Now create as many pages as you like and include this file to create header. For example now your
test.php file can have following content.
<html>
<body>
<?php
include("menu.php");
?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
The require() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the require() function
generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions.
It is recommended to use the require() function instead of include(), because scripts should
not continue executing if files are missing or misnamed.
You can try using above example with require() function and it will generate same result. But
if you will try following two examples where file does not exist then you will get different
results.
<html>
<body>
<?php
include("xxmenu.php");
?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
<html>
<body>
<?php
require("xxmenu.php");
?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
NOTE:-You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.
What is MySQL?
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.
Database Queries
Connecting to databases
To connect PHP with database, four important things must be taken place. Those are:-
Define constants
Create connection using mysql_connect.
Select database.
Close connection.
1. Define constants
To connect php with database, defining constants is very important. Constants that must be defined are:-
<?php
?>
After defining constants using php, opening or creating connection is very important. To open or create
database connection, we use mysql_connect function.
db_server,db_user,db_pass.
Db_server:-The host name running database server
Db_user:-The username accessing the database
Db_pass:-The password of the user accessing the database.
From the above the host name running database server is ―localhost‖, the username accessing the database
is ―user‖, and the password of the user accessing the database is empty. Connection can opened or created
as follows:
$connection=mysql_connect(db_server,db_user,db_pass);
3. Select database
Once you establish a connection with a database server then it is required to select a particular database
where your all the tables are associated.
This is required because there may be multiple databases residing on a single server and you can do work
with a single database at a time.
$db_select=mysql_select_db(db_name,$connection);
Its simplest function mysql_close PHP provides to close a database connection. This function takes
connection resource returned by mysql_connect function. For example, to close the connection that you
use in the above; you use mysql_close function as follows:-
mysql_close($connection);
To create and delete a database you should have admin privilege. Its very easy to create a new MySQL
database. PHP uses mysql_query function to create a MySQL database. For example to create the
database test_db using php, you can write as follows:-
<?php
define("db_server","localhost");
define("db_user","root");
define("db_pass","");
$connection=mysql_connect(db_server,db_user,db_pass);
if(!$connection)
if(! $retval ) {
mysql_close $connection);
?>
To create tables in the new database you need to do the same thing as creating the database. First create
the SQL query to create the tables then execute the query using mysql_query() function.
<?php
define("db_server","localhost");
define("db_user","root");
define("db_pass","");
define("db_name","test_db");
$con=mysql_connect(db_server,db_user,db_pass);
if(!$con){
die("not connected".mysql_query());
$sqldb=mysql_select_db(db_name,$con);
if (!$sqldb){
die("incorrectly selected".mysql_error());
$retval = mysql_query($sql,$con);
if(!$retval ) {
?>
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and execute those commands.
Consider the following content in sql_query.txt file.
<?php
define("db_server","localhost");
define("db_user","root");
define("db_pass","");
define("db_name","test_db");
$con=mysql_connect(db_server,db_user,db_pass);
if(!$con){
die("not connected".mysql_query());
$sqldb=mysql_select_db(db_name,$con);
if (!$sqldb){
die("incorrectly selected".mysql_error());
$query_file = 'sql_query.txt';
fclose($fp);
$retval = mysql_query($sql,$con);
if(!$retval ) {
?>
Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function
mysql_query. Below a simple example to insert a record into employee table.
Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function
mysql_query. You have several options to fetch data from MySQL.
The most frequently used option is to use function mysql_fetch_array(). This function returns row as an
associative array, a numeric array, or both. This function returns FALSE if there are no more rows.
$retval = mysql_query($sql,$con);
if(!$retval ) {
"--------------------------------<br>";
The content of the rows are assigned to the variable $row and the values in row are then printed.Always
remember to put curly brackets when you want to insert an array value directly into a string.
PHP provides another function called mysql_fetch_assoc() which also returns the row as an associative
array.
Using mysql_fetch_assoc()
while($row = mysql_fetch_assoc($retval)) {
"--------------------------------<br>";
Using MYSQL_NUM
"--------------------------------<br>";
Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP function
mysql_query.
Below is a simple example to delete records into employee table. To delete a record in any table it is
required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.
$emp_id = $_POST['emp_id'];
If a database is no longer required then it can be deleted forever. You can use pass an SQL command to
mysql_query to delete a database.
Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function
mysql_query.
Below is a simple example to update records into employee table. To update a record in any table it is
required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.
$emp_id=$_POST['emp_id‘];
$emp_salary = $_POST['emp_salary‘];
$sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". "WHERE emp_id = $emp_id" ;