0% found this document useful (0 votes)
6 views76 pages

SE - WEB - Chapter 5 PHPv1

The document provides an overview of server-side scripting, specifically focusing on PHP as a web development language. It explains how PHP processes requests, handles variables, and utilizes control structures like loops and conditional statements. Additionally, it covers array management and built-in PHP arrays for handling server and user data.

Uploaded by

gemechisgadisa77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views76 pages

SE - WEB - Chapter 5 PHPv1

The document provides an overview of server-side scripting, specifically focusing on PHP as a web development language. It explains how PHP processes requests, handles variables, and utilizes control structures like loops and conditional statements. Additionally, it covers array management and built-in PHP arrays for handling server and user data.

Uploaded by

gemechisgadisa77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Jimma University

Faculty of Computing and Informatics


Software Engineering Program

Web Design and Programming

Jimma, Ethiopia.
Server side scripting

 It is a web technology that allows custom HTML to be delivered to a client machine where
the code that generates processed on the web server.
 Server-side language code remains on the web server. After it has been processed, the server
sends only the output of the script to the user as HTML format.
 Server-side language brings websites to life in the following ways:
 Uploading files through a web page
 Reading and writing to files
 Displaying and updating information dynamically
 Sending feedback from your website directly to your mailbox
 Using a database to display and store information
 Making websites searchable. Etc…

2
How Server side scripting work

 When a PHP–driven website is visited, it sets in train the following sequence of events:
 The browser sends a request to the web server.
 The web server hands the request to the PHP engine, which is in the server.
 The PHP engine processes the code. It might also query a database
 The server sends the completed page back to the browser.

3
Introduction to PHP

 PHP is the web development language written by and for Web developers.
 PHP stands for Hypertext Preprocessor. PHP is currently in its fifth major version called
PHP5.
 PHP is a server-side scripting language, which can be embedded in HTML or used as a
standalone binary. it is a server-side scripting language, which means that the scripts are
executed on the server.
 The server reads the PHP code and outputs browser-friendly HTML
 Because PHP scripts execute on the server, PHP can dynamically create the HTML code
that generates the Web page. This 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, avoiding the knowledge of technical details for
connecting to a database: i.e MySQL, PostgreSQL, oracle, Sybase.
Cont...

 With PHP you can store data on the server as files or in databases.
 PHP supports a large number of major protocols such as POP3, IMAP.
 PHP4 added support for Java and distributed object architectures (COM and CORBA),
making n-tier development a possibility for the first time.
 Create a customized user experience for visitors based on information that you have
gathered from them.
What is a PHP File?
 ? PHP files may contain text, HTML tags and scripts
 ? PHP files are returned to the browser as plain HTML
 ? PHP files have a file extension of ".php", ".php3", or ".phtml"
PHP Syntax

 The PHP code is enclosed in special start and end processing instructions <?php and ?>
 You can add PHP code to your web page by using tags, similar to other tags in the HTML
file.
 The PHP code section is enclosed in PHP tags with the following form:
 <?php PHP statements ?>
 PHP code is executed on the server, generating HTML which is then sent to the client. The
client would receive the results of running that script, but would not know what the
underlying code was.
 For example, you can add the following PHP section to your HTML file.
 <?php echo “This line brought to you by PHP”; ?>
 Web pages that contains PHP should be saved with .php extension
<?php echo “<p>Order processed. </p>”; ?>
Cont...

 index.php on the server


Output Statements

 The two most basic ways for displaying output in PHP are echo and print. Both can be used
either with parentheses or without.
 echo outputitem1 and echo (output);
 print output; and print(output);
 Example: different ways of echo and print PHP supports two types of comments:
• single-line comment (short
echo 123; //output: 123
comment) by using the # or //
echo “Hello World!”; //output: Hello world! • multi-line comment (long
echo “Hello”, ”World!”; //output: Hello World! comment) by using /* */

echo Hello World!; //error, string should be in quotes


The command print is very similar to echo, with
print (“Hello world!”); //output: Hello world! two important differences:
Unlike echo, print can accept only one argument.
print “Hello world!”; //output: Hello world! Unlike echo, print returns a value, which
represents whether the print statement
succeeded.
Variable Declaration

 In PHP, all variable names should start with a dollar sign ($). This tells PHP that it
is a variable name.
 To store information in a variable, use a single equal sign (=).
 For example:
$age = 21;
$price = 20.52;
$temperature = -5;
$name = “Clark Kent”;
echo “Your age is $age”;
 PHP is a loosely typed language. This means that a single variable may contain any
type of data.
Cont...

 PHP has a total of eight types: integers, doubles, Booleans, strings, arrays, objects, NULL, and
resources:
 Integers are whole numbers, without a decimal point, like 495.

 Doubles are floating-point numbers, like 3.14159 or 49.0.

 Booleans have only two possible values: TRUE and FALSE.

 Strings are sequences of characters, like “PHP is very interesting”.

 Arrays are named and indexed collections of other values.

 Objects are instances of programmer-defined classes.

 Resources are special variables that hold references to resources external to PHP such as
database connections.
 NULL is a special type that only has one value: NULL.
Cont...

Removing Variables
 You can uncreate the variable by using this statement:
unset($age);
 After this statement, the variable $age no longer exists. If you try to echo it, you get an
“undefined variable” notice.
 You can unset more than one variable at once, as follows:
unset($age, $name, $address);
 Sometimes you just need to know whether a variable exists or what type of data is in the variable.
 Here are some common ways to test variables:
 isset($varname) - true if variable is set, even if nothing is stored in it.
 empty($varname) - true if value is 0 or is a string with no characters in it or is not set.
 You can also test what type of data is in the variable. is_integer($var), is_array($var2),
is_bool($var):
Cont...

 Constants are set by using the define statement.


 The general format is as follows:
define(“constantname”, ”constantvalue”);
 For example, to set a constant with the weather, use the following statement:
define(“PI”,”3.141”); print(PI); and echo PI;
 This statement creates a constant called PI and sets its value to “3.141”.
 unlike variables, constant names do not begin with a dollar sign ($).
 When you echo a constant, you can’t enclose it in quotes.
 echo “The value of PI is $”, INTEREST;
Using Operators

 Assignment Operators (=)

$my_var = 4;
 Arithmetic Operators (+, - , / , * )

$my_var = 4; $my_var2= 5;
$sum= $my_var + $my_var2;
echo $sum;
 Comparison Operators (==, <=, >=, <, >,!=)

$my_var2 <= $my_var


 Combination Arithmetic & Assignment Operators (.= , /=, %=, +=,-=, etc…)

$my_str.="hello";
$my_str = $my_str . "hello";
 Pre- and Post-Increment and Decrement operators
Conditional Statements

 if Statements: We can use an if statement to make a decision.


 if..else statements: An else statement allows you to define an alternative action to be taken
when the condition in an if statement is false.
 else if Statements: For many of the decisions we make, there are more than two options.

if ($day == 5)
print(“Five golden rings<BR>”);
elseif ($day == 4)
print(“Four calling birds<BR>”);
elseif ($day == 3)
print(“Three French hens<BR>”);
elseif ($day == 2)
print(“Two turtledoves<BR>”);
elseif ($day == 1)
print(“A partridge in a pear tree<BR>”);
Cont...

switch statements: The switch statement works in a similar way to the if statement, but
allows the condition to take more than two values.
<?php
$mood = “happy";
switch ($mood) {
case "happy":
echo "Hooray, I'm in a good mood";
break;
case "sad":
echo "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
break; }
?>
Using Loops

 Loop statements are designed to enable you to achieve repetitive tasks.


 A loop will continue to operate until a condition is achieved, or you explicitly choose
to exit the loop.
 There are three types of loops:
 for loop: Sets up a counter; repeats a block of statements until the counter reaches a
specified number
 while loop: Sets up a condition; checks the condition, and if it’s true, repeats a block
of statements until the condition becomes false
 do..while loop: Sets up a condition; executes a block of statements; checks the
condition; if the condition is true, repeats the block of statements until the condition
becomes false
Cont...

 for ($i = 1; $i <= 3; $i++) { $count = 1;


while ($count <= 10) {
echo “$i. Hello World!<br>”;
print(“count is $count<BR>”);
} $count = $count + 1;
 You can use the following nested loop statements: }
for($i=1; $i<=9; $i++){
$count = 1;
for($j=1; $j<=9; $j++){
do{
$result = $i * $j; print(“count is $count<BR>”);
echo “$i x $j = $result\n”; $count = $count + 1;
}while ($count <= 10);
}
}
Cont...

 PHP provides two statements :


 break: breaks completely out of a loop and continues with the script statements
after the loop.
 continue: stops current iteration and goes back to condition check. If condition
check is true, it will go to the next iteration.
 The break and continue statements are usually used in conditional statements.
 In particular, break is used most often in switch statements.
Cont...

$counter = 0;
while ( $counter < 5 ) {
$counter++; The output of this statement is the following:
Last line in loop: counter=1
if ( $counter == 3 ) {
Last line in loop: counter=2
echo “break\n”; break
break; First line after loop
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n\n”;
Cont...

Exercise
1. Write a while loop that displays prime numbers between 1 and 100
2. Write a for loop that displays the squared and cubed value of numbers between
0 and 100.
3. Write a do while loop that calculates the factorial of a number.
4. Write a loop that gets the factors of a given number.
ARRAY

 In addition to numerical indexes, PHP also supports associative arrays.


 Associative arrays can have almost anything as the array indices, but typically use strings.
Creating Arrays
 There are different ways to create an array in a PHP script:
 by assigning a value into one (and thereby implicitly creating it),
 by using the array() construct, or
 by calling a function that happens to return an array as its value.
 Example
 $products[0] = “Tires”;
$products[1] = “Oil”;
 $fruit = array(“apple”, “orange”, “banana”, “pear”);
Cont...

Associative Arrays: PHP also supports associative arrays.


 In an associative array, we can associate any key or index we want with each value.
 An associative array can be viewed as a list of key/value pairs, stored as follows:
$arrayname[‘key1’] = value1;
$arrayname[‘key2’] = value2;
$arrayname[‘key3’] = value3;
 Initializing an Associative Array
$person = array("name" => “John", "occupation" => "engineer", "age" => 30, "special power" =>
"x-ray vision");
 You can reference specific elements of an associative array using the specific key.
 Example: to access associative array element
echo $person['occupation']; //output: engineer
Cont...

Walking through Array


 One is by using loop together with array index.
 Using foreach to walk through an array
foreach ( $arrayname as $keyname => $valuename) {
block of statements;
}
 Example: foreach loop
$population = array( “number1”=>25000, “number2”=>20000, “number3”=>5000);
foreach($population as $key => $value) {
echo “$key: $value.<br>”;
}
Cont...

Determining Size of Array


 You can find out the size of your array by using either the count statement or a sizeof
statement.
$n = count($arrayname);
$n = sizeof($arrayname);
Built-in Arrays
 PHP has several built-in arrays that you can use when writing PHP scripts. Different types
of information are stored in builtin arrays.
 For example, information about your server (such as headers, paths, and script locations) is
stored in an array called $_SERVER
Cont...

 $GLOBALS: Contains all the global variables. For example, if you use the statement,
$testvar = 1, you can then access the variable as $GLOBALS [‘testvar’].
 $ _POST: Contains all the variables contained in a form if the form uses method=”post”.
 $HTTP_POST_VARS: Same as $ _POST.
 $ _GET: Contains all the variables passed from a previous page as part of the URL. This
includes variables passed in a form using method=”get”.
 $HTTP_GET_VARS: Same as $ _GET.
 $ _COOKIE: Contains all the cookie variables.
 $HTTP_COOKIE_VARS: Same as $ _COOKIE.
 $ _SESSION: Contains all the session variables.
 $HTTP_SESSION_VARS: Same as $ _SESSION.
Cont...

 $_REQUEST: Contains all the variables together that are in $_POST, $_GET, and
$_SESSION.
 $_FILES: Contains the names of files that have been uploaded.
 $HTTP_FILES_VARS: Same as $_FILES.
 $_SERVER: Contains information about your server. Because your Web server provides the
information, the information that’s available depends on what server you’re using.
 $HTTP_SERVER_VARS: Same as $_SERVER.
 $_ENV: Contains information provided by your operating system, such as the operating
system name, the system drive, and the path to your temp directory. This info varies
depending on your operating system
 $HTTP_ENV_VARS: Same as $_ENV.
Cont...

 The $_SERVER and $_ENV arrays contain different information, depending on the
server and operating system you’re using.
 You can see what information is in the arrays for your particular server and operating
system by using the following statements:
foreach($_SERVER as $key =>$value)
echo “Key=$key, Value=$value\n”;
Function in PHP

 A function is a group of PHP statements that perform a specific task.


 You can use the function wherever you need to perform the task.

function functionname($argument1, $argument2, ….){


block of statements;
function addNumbers($a, $b){
return value; $sum = $a +$b;
return $sum
} }
Calling a function
 The following line is the simplest possible call to a function:
addNumbers(10,4);
Pass by Reference Versus Pass by Value(Cont...)

 If we want to write a function called increment() that allows us to


increment a value, we might be tempted to try writing it as follows:
function increment($value, $amount){
$value = $value +$amount;}
 The normal way that function parameters are called is called pass by value. It is a copy of
the original.
 You are free to modify this value in any way, but the value of the original variable
outside the function remains unchanged.
 The better approach is to use pass by reference.
 When a parameter is passed by reference, rather than creating a new variable, the
function receives a reference to the original variable.
 We specify a pass by reference by placing an ampersand (&) before the parameter name
Cont...

 Example:
function increment(&$value, $amount = 1){
$value = $value +$amount;
}
$value = 10;
increment ($value, 1);
echo $value; //prints 11
Variable Scope

 A variable declared within a function remains local to that function.

 PHP has fairly simple rules:

 Variables declared inside a function are in scope from the statement in which they
are declared to the closing brace at the end of the function. This is called
function scope and are called local variables.
 Variables declared outside of functions are in scope of the statement in which
they are declared to the end of the file, but not inside functions. This is called
global scope and are called global variables.
 The keyword global can be used to manually specify that a variable defined or
Example: local variable

<?php
$num=50;
function test(){
$testvari = "this is a test variable";
echo “Num is ”, $num; //output: Num is
}
echo "test variable: $testvar"; //output: test variable:
echo “Num is ”, $num; //output: Num is 50
?>
 The value of the variable $testvar is not printed. This is because no such variable exists
outside the test() function.
 Similarly, a variable declared outside a function will not automatically be available within it.
Cont...

 If you want a variable created within a function to be global, we can use the
keyword global as follows:
function fn(){
global $var;
$var = “contents”;
echo “inside the function, \$var = “.$var.”<br>”;
}
fn();
echo “outside the function, \$var = “.$var.”<br>”;
output:
inside the function, $var = contents
outside the function, $var = contents
Cont...

 In PHP global variables must be declared global inside a function if they are going
to be used in that function.
<?php
$a = 1; $b = 2;
function Sum() {
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b; ?>
 The above script will output "3".
 By declaring $a and $b global within the function, all references to either variable
will refer to the global version.
Cont...

 A second way to access variables from the global scope is to use the special PHP-
defined $GLOBALS array.
 The previous example can be rewritten as:
<?php
$a = 1; $b = 2;
function Sum(){
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>
Execirse

 Write a function that accepts a number and returns the squared and cubed value of

the number.

 Write a function that accepts a number as parameter and then calculates the factorial

of the number and return it.


Cookies and Sessions

Cookies
 A cookie is a small piece of information that is retained on the client machine, either
in the browser’s application memory or as a small file written to the user’s hard disk.
 A cookie is stored by the user's browser in compliance with a request from a server
or script.
 A cookie is often used to identify a user. Each time the same computer requests a
page with a browser, it will send the cookie too.
 You store cookies by using the setcookie function. The general format is as follows:
setcookie(“variable”, ”value”);
 For example, the following statement stores the pair city=Jimma in the cookie file on
the user’s computer: setcookie(“city”,”Jimma”);
Cont...

 You can access the cookie using a built-in array called $_COOKIE.
 The next Web page can display the information from the cookie by using the following statement.
 echo “Your home city is “.$_COOKIE[‘city’]; //Your home city is Jimma
 Setting expiration dates
 If you want the information stored in a cookie to remain in a file on the user’s computer after the
user leaves your Web site, set your cookie with an expiration time, as follows:
 setcookie(“variable”, ”value”, expiretime); The expiretime value sets the time when the cookie
expires. setcookie(“state”, ”CA”, time()+3600); #expires in one hour
 Deleting a Cookie setcookie(“Name”, $Name, time()+(3*86400)) #expires 3 days

 Officially, to delete a cookie, you should call setcookie() with the name argument only:

setcookie(“city");
 This approach does not always work well, however, and should not be relied on. It is safest to set the
cookie with a date you are sure has already expired: setcookie(“city", "", time()-60);
Session(Cont...)

 A session is the time that a user spends at your Web site.


 Users may view many Web pages between the time they enter your site and leave
it.
 To make session information available, PHP does the following:
 PHP assigns a session ID number.
The number is a really long number that is unique for the user and that no one
could possibly guess. The session ID is stored in a PHP system variable
named PHPSESSID.
 PHP stores the variables that you want saved for the session in a file on the
server.
 The file is named with the session ID number.
 PHP passes the session ID number to every page.
Opening and closing sessions

 You should open a session at the beginning of each Web page. Open the session with the
session_start function, as follows:
 session_start();
 The function first checks for an existing session ID number.
 If it finds one, it sets up the session variables.
If it doesn’t find one, it starts a new session by creating a new session ID number.
 To avoid an error, the session_start function must be called before any output is sent.
 This means that it is must be the first line code in your program.
 You may want to restrict your site to users with a valid user ID and password.
 For restricted sessions that users log into, you often want users to log out when they’re
finished.
 To close a session, use the following statement wherever to want to close the session:
session_destroy();
Cont...

Using PHP session variables

 To save a variable in a session so that it’s available on later web pages, store the value in the
$_SESSION array, as follows:

 $_SESSION[‘varname’] = “John Bonson”;

 When you open a session on any subsequent web page, the values stored in the
$_SESSION array are available.

 If you want to stop storing any variable at any time, you can unset the variable by using
the following statement:

 unset($_SESSION[‘varname’]);
Working with Forms

 We use one of two methods to submit form information. The methods pass the form data
differently and have different advantages and disadvantages
 GET method:
 The form data is passed by adding it to the URL that calls the form-processing script.
 For example, the URL may look like this:
processform.php?lname=Smith&fname=Goliath
 The advantages of this method are simplicity and speed.
 The disadvantages are that
less data can be passed and
the information is displayed in the browser, which can be a security problem in some
situations.
Cont...

 POST method:
 The form data is passed as a package in a separate communication with the
processing script.
 The advantages of this method are unlimited information passing and security of
the data.
 The disadvantages are the additional overhead and slower speed.
 The form data is available in the processing script in the PHP built-in arrays.
 Information from forms that use the POST method is available in the built-in array
called $_POST.
 If your form uses the GET method, the information is available in the array $_GET.
 Both types of form information are also stored in an array called $_REQUEST.
 You get information from the array by using the form field name as the array key.
Cont...

 The syntax is:


$_POST[“form element name”]
$_GET[“form element name”]
 For example, suppose that you echo the following field in your form that uses the POST
method:
<input type=’text’ name=’firstName’>;
 The value entered in this textbox can be accessed by
$_POST[‘firstName’]
 This contains the text the user typed into the field.
 If the form uses GET method, the above textbox can be accessed as
$_GET[“firstName”]
Database Programming

 PHP is particularly strong in its ability to interact with databases. PHP supports pretty much
every database out there. The most commonly used database with PHP is MySQL
 MySQL is a free and open source database that has a lot of users especially for web
applications.
 Whichever database you’re using, the steps to interact with a database are similar:
 Connect to the database.
 Send an SQL query that contains instructions for the database software.
 If you retrieved data from the database, process the data.
 Close the connection to the database.
Connecting to the database

 The first step in a database interaction is connecting to the database. You have to use a PHP

function to connect to the database.


 To make the connection, you need to supply the function with three things:
 Location:
The database may not be on the same computer where PHP is installed.
• Therefore, you need to tell the PHP connect function the name of the computer
where the database is located.
You can supply either a domain name (such as mycompany.com) or an IP address (such
as 172.17.204.2).
If the database is on the same computer as PHP, you can use localhost for the hostname.
 Account name: You must provide a valid account name that can be used to access the
database.

Cont...

 The syntax for creating connection to MySQL database:


 $connect = mysql_connect($host, $account, $password);
 After connecting to the database, the next step is selecting database. An RDBMS can
create and maintain many databases, so you need to tell it which database you want to
use.
 The syntax for selecting database is:
 $db = mysql_select_db(string database, [int database_connection]);
<?php
$con = mysql_connect("localhost",“root",“vertrigo");
mysql_select_db(“books”);
//other statements
?>
Querying the Database (Cont...)

 To actually perform the query, we can use the mysql_query() function.


 Before doing this, however, it’s a good idea to set up the query you want to run:
 $query = “select * from books“;
 We can now run the query:
 $result = mysql_query($query);
 The mysql_query() function has the following prototype:
 int mysql_query(string query, [int dbconnection] );
 You pass it the query you want to run, and optionally, the database connection created.
 If connection isn’t specified, the function will use the last opened link.
 If there isn’t one, the function will open the default one as if you had called
mysql_connect().
Cont...

 You might want to use the mysql_db_query() function instead.


 int mysql_db_query(string database, string query, [int dbconnection] );
It’s very similar but allows you to specify which database you would like to
run the query on.
 It is like a combination of the mysql_select_db() and mysql_query() functions.
 Both of these functions return a result identifier that allows you to retrieve the
query results or false on failure.
 Example: executing query
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
Cont...

 Putting all together:


<?php
$account = “david”;
$password = “gotago”;
$host= “localhost”;
$connect = mysql_connect($host, $account, $password);
mysql_select_db(“Catalog”, $connect);
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
//other code
?>
Processing Data

 To process the data returned from database, you need to get it from the temporary
table where it is placed when the SQL query is executed.
 We use PHP database functions to get the data from the temporary table.
 The data is stored in the temporary table in rows and columns.
 You can use PHP functions to retrieve one row from the table and store it in an
array
The array has the field names as the array keys.
 For MySQL, the statement is as follows:
 $row = mysql_fetch_array($result);
 It requires one of the mysql_fetch functions to make the data fully available to PHP.
Cont...

 The fetching functions of PHP are as follows:


 mysql_fetch_array: returns rows as associative or numbered array
 mysql_fetch_assoc: returns rows as associative array
 mysql_fetch_row: returns row as an enumerated array
 mysql_fetch_object: returns row as an object
 mysql_result: returns one cell of data
 The most useful fetching function, mysql_fetch_array, offers the choice of results as an
associative or an enumerated array or both. The default is returning as both (index or key).
$query = “SELECT ID, LastName, FirstName FROM Customers”;
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
Cont...

$query = “SELECT ID, LastName, FirstName FROM users WHERE


Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
$query=“SELECT ID, LastName, FirstName FROM Customers”;
$result = mysql_query($query);
while ($row = mysql_fetch_object($result)){
echo $row->ID; $query = “SELECT count(*) FROM Customers”;
echo $row->FirstName; $db_result = mysql_query($query);
echo $row->LastName<BR>\n”; $datapoint = mysql_result($db_result, 0, 0);
}
$query = “SELECT ID, LastName, FirstName FROM Customers”;
$result = mysql_query($query);
while ($name_row = mysql_fetch_row($result)) {
print(“$name_row[0] $name_row[1] $name_row[2]<BR>\n”);
}
 Example: a program that retrieves data from database and display in table

<?php
$con = mysql_connect("localhost","root","vertrigo");
mysql_select_db(“Sales”);
$query = “SELECT * FROM Customers”;
$result = mysql_query($query);
echo(“<TABLE border=’1’>”);
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo('<TD> '.$row["ID"].' </TD> ');
echo('<TD>'. $row["firstname"] . '</TD> ');
echo('<TD> '.$row["lastname"] .'</TD> ');
echo('<TD> '.$row["sex"].' </TD> ');
echo "</tr>";
} echo(“</TABLE><BR>\n”); ?>
Inserting Data into Database

 Inserting new items into the database is remarkably similar to getting items out of the
database.
 You follow the same basic steps
 make a connection,
 send a query, and
 check the results.
 In this case, the query you send will be an INSERT rather than a SELECT.
$query = “INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st)”;
$result = mysql_query($query);
if (mysql_affected_rows($result) >= 1)
echo ‘<P>Your information has been saved.</P>’;
else
echo ‘<P>Something went wrong with your signup attempt.</P>’;
Cont...

 In addition to insertion, you can do many other operations on database using SQL
 SELECT item_list FROM table_list WHERE search_condition;

select lname, fname, balance from account where balance > 10000
 CREATE TABLE table-name (column-name data-type, .... )

Create table customer(lname varchar(20), fname varchar(20), branch varchar(30), balance number);
 INSERT INTO table_name(column_names) VALUES (value_list)

INSERT INTO account (lname, fname, branch, balance) VALUES ('john', 'smith', 101, 10000)
 DELETE FROM table_name WHERE search_condition

DELETE FROM account where fname = 'john' and lname = 'smith'


 UPDATE table_name SET column_names expression WHERE condition

UPDATE account SET balance = balance * 1.06 where balance > 1000
Closing the connection

 Any open database connections are closed when the script ends.
 However, it is good programming practice to close the connections in the script to
avoid any possible problems.
 You close database connections with a PHP function
 For example, for MySQL, use the following function to close a database
connection:
mysql_close($connect);
Other PHP-Database Functions

 mysql_affected_rows () — Get number of affected rows in previous MySQL operation.


 It helps you to know how many rows have been deleted, inserted, modified, etc. by
the last mysql_query() operation.
int mysql_affected_rows ( [resource link_identifier])
 mysql_affected_rows() returns the number of rows affected by the last INSERT,
UPDATE or DELETE query associated with link_identifier.
 mysql_create_db () — Create a MySQL database. The syntax is:
 bool mysql_create_db (string databasename [, resource link_identifier]);
 mysql_create_db() attempts to create a new database on the server associated with
the specified link identifier.
Cont...

 mysql_drop_db — Drop (delete) a MySQL database


 mysql_drop_db() attempts to drop (remove) an entire database from the server
associated with the specified link identifier.
 bool mysql_drop_db (string database_name [, resource link_identifier])
 mysql_num_rows — Get number of rows in result.
 The syntax is: int mysql_num_rows (resource result);
 mysql_num_rows() returns the number of rows in a result set.
This command is only valid for SELECT statements.
 mysql_num_fields — Get number of fields in result.
 The syntax is: int mysql_num_fields (resource result);
Cont...

 mysql_field_name — Get the name of the specified field in a result.

string mysql_field_name (resource result, int field_index)


mysql_field_name() returns the name of the specified field index.

• field_index is the numerical offset of the field. Note that field_index starts at 0.
 mysql_list_tables — List tables in a MySQL database.

resource mysql_list_tables (string database [, resource link_identifier])


 mysql_list_tables() takes a database name and returns a result pointer much like the
mysql_query() function.
 You can use the mysql_tablename() function to extract the actual table names from the
result pointer, or any other result table function such as mysql_fetch_assoc().
Cont...

<?php
$link = mysql_connect('localhost', 'root', 'vertrigo');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_row($db_list)) {
echo $row[0] . "<br>";
}
$tn = mysql_list_tables(“lab", $link);
while($row = mysql_fetch_array($tn, MYSQL_NUM)){
echo $row[0]."<br>";
}
?>
Working with Files

Uploading Files
 You may want users to upload files to your Web site. For example, you may want users to be
able to upload resumes to your job-search Web site or pictures to your photo album Web site.
 You can display a form that allows a user to upload a file by using an HTML form designed
for that purpose.
 The general format of the form is as follows:
<form enctype=”multipart/form-data” action=”file.php” method=”post”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”30000”>
<input type=”file” name=”user_file”>
<input type=”submit” value=”Upload File”>
</form>
Cont...

 Notice the following points regarding the form:


 The enctype attribute is used in the form tag. You must set this attribute to
multipart/form-data when uploading a file.
 A hidden field is included that sends a value (in bytes) for MAX_FILE_SIZE. If the
user tries to upload a file that is larger than this value, it won’t upload.
 The submission method should be POST.
 The input field that uploads the file is of type file.
Cont...

 When the user submits the form, the file is uploaded to a temporary location.
 The script that processes the form needs to copy the file to another location because the
temporary file is deleted as soon as the script is finished.
 You can use phpinfo() to see where the temporary files are stored.
 If you don’t like the location of the temporary directory, you can change it by changing
upload_tmp_dir in the php.ini file.
 If no directory is specified in php.ini, a default temporary directory is used.
Accessing Information About An Uploaded File(Cont...)

 Along with the file, information about the file is sent with the form.
 This information is stored in the PHP built-in array called $_FILES.
An array of information is available for each file that was uploaded.
 You can obtain the information from the array by using the name of the field.
$_FILES[‘fieldname’][‘name’] – contains filename
$_FILES[‘fieldname’][‘type’] – contains type of file
$_FILES[‘fieldname’][‘tmp_name’] – contains temporary location of file
$_FILES[‘fieldname’][‘size’] – contains size of file
 For example, suppose you use the following field to upload a file:
<input type=”file” name=”user_file”>
Moving Uploaded Files To Their Destination

 Since the temporary file created during upload is deleted when the script finishes, it
has to be moved to another location if you want to store it permanently.
 The general format of the statement that moves the file is as follows:
 move_uploaded_file(path/tempfilename, path/permfilename);
 You can use the following statement to move the file to your desired location, in this
case, c:\data\new_file.txt:
 move_uploaded_file($_FILES[‘user_file’][‘tmp_name’], ‘c:/data/new_file.txt’);
Working with Date and Time

 PHP's time() function gives you all the information that you need about the current date and time. It
requires no arguments and returns an integer.
 For us humans, the returned number is a little hard on the eyes, but it's extremely useful nonetheless.
echo time(); //1060751270
 This represents August 12th, 2003 at 10:07PM
 PHP offers excellent tools to convert a timestamp into a form that humans are comfortable with.
 There are two ways to get useful information from timestamp:
Using getdate() function
Using date() function
 The getdate() function optionally accepts a timestamp and returns an associative array
containing information about the date.
 If you omit the timestamp, getdate() works with the current timestamp as returned by time().
Cont...

 The table lists the elements contained in the associative array returned by getdate().
Key Description Example
seconds Seconds past the minute (0–59) 28
minutes Minutes past the hour (0–59) 7
hours Hours of the day (0–23) 12
mday Day of the month (1–31) 20
wday Day of the week (0–6) 4
mon Month of the year (1–12) 1
year Year (4 digits) 2000
yday Day of year (0–365) 19
weekday Day of the week (name) Thursday
month Month of the year (name) January
0 Timestamp 948370048
Cont...

 Example: Acquiring date information with getdate() The output is:


<?php seconds = 53
minutes = 26
$date_array = getdate(); //no argument passed, today's date used
hours = 11
foreach ($date_array as $key => $val) mday = 20
echo "$key = $val <br>"; wday = 2
mon = 11
?>
year = 2023
<?php yday = 332
echo "Today's date: ".$date_array['mon']."/".$date_array['mday']. weekday = Tuesday
month = November
"/".$date_array['year'];
0 = 1322555213
?> Today's date: 11/20/2023
Mathematical Functions

 PHP has built-in mathematical constants, and trigonometric, logarithmic, and base conversion
functions. PHP constants are:
function Behavior
pow() Takes two numerical arguments and returns the first argument raised to the power
of the second. The value of pow($x, $y) is xy.
exp() Takes a single argument and raises e to that power. The value of exp($x) is ex.
log() The “natural log” function. Takes a single argument and returns its base e logarithm.
If ey = x, then the value of log($x) is y.
log10() Takes a single argument and returns its base-10 logarithm. If 10 y = x, then the value
of log10($x) is y.
pi() Takes no arguments and returns an approximation of pi (3.1415926535898). Can be
used interchangeably with the constant M_PI.
sin() Takes a numerical argument in radians and returns the sine of the argument as a
double.
Cont...

cos() Takes a numerical argument in radians and returns the cosine of the argument as a
double.
tan() Takes a numerical argument in radians and returns the tangent of the argument as a double.
asin() Takes a numerical argument and returns the arcsine of the argument in radians. Inputs must be
between –1.0 and 1.0, otherwise, it will return a result of NAN. Results are in the range –pi / 2 to pi /
2.
acos() Takes a numerical argument and returns the arccosine of the argument in radians. Inputs must be
between –1.0 and 1.0, otherwise, it will return a result of NAN. Results are in the range 0 to pi.

atan() Takes a numerical argument and returns the arctangent of the argument in radians. Results are in
the range –pi / 2 to pi / 2.
atan2() A variant of atan() that takes two arguments. Atan($y, $x) is identical to atan($y/$x) when $x is
positive, but the quadrant of atan2’s result depends on the signs of both $y and $x. Range of the
result is from –pi to pi.
sqrt ($num) Returns square root of a number.
floor($float) Returns the next lowest integer value by rounding down value.
ceil($float) Returns the next highest integer value by rounding up value.
Cont...

 Example: Function Behavior


BinDec() Takes a single string argument representing a binary
echo pow(2, 8); //256
(base 2) integer, and returns a string representation
echo log10(100); //2 of that number in base 10.
echo sqrt(9); // 3 DecBin() Like BinDec(), but converts from base 10 to base 2.
echo ceil(4.3); // 5 OctDec() Like BinDec(), but converts from base 8 to base 10.
DecOct() Like BinDec(), but converts from base 10 to base 8.
echo round(3.4); // 3
HexDec() Like BinDec(), but converts from base 16 to base 10.
echo round(3.6); // 4 DecHex() Like BinDec(), but converts from base 10 to base 16.
echo round(1.95583, 2); // 1.96 Base_convert() Takes a string argument (the integer to be converted)
echo round(1241757, -3); // 1242000 and two integer arguments (the original base, and
the desired base). Returns a string representing the
echo pi(); // 3.1415926535898
converted number—digits higher than 9 (from 10 to
35) are represented by the letters a–z. Both the
original and desired bases must be in the range 2–36.
Reusing Code

 One of the goals of software engineers is to reuse code in instead of writing new code.
 Reusing existing code reduces costs, increases reliability, and improves consistency.
Ideally, a new project is created by combining existing reusable components, with a
minimum of development from scratch.
 PHP provides two very simple, yet very useful, statements to allow you to reuse any type
of code.
 Using include or require statement, you can load a file into your PHP script.
The file can contain anything you would normally type in a script including PHP
statements, text, HTML tags, etc
 The two functions are identical in every way, except how they handle errors:
 include() generates a warning, but the script will continue execution
 require() generates a fatal error, and the script will stop
Cont...

 These two functions are used to create functions, headers, footers, or elements that will be reused
on multiple pages
Using require:
 The following code is stored in a file named reusable.php:
<?php
echo “Here is a very simple PHP statement. <br>”;
?>
 The following code is stored in a file called main.php:
<?php
echo “This is the main file. <br> “;
require(“reusable.php”);
echo ”The script will end now. <br>”;
Using include(Cont...)

 The statements require() and include() are very similar, but some important
differences exist in the way they work.
 For example, we might decide that we are opening files a lot and rather than
retyping the same lines of code every time, we want an include file to open them
for us.
 Our include file might be called openfile.php and resemble the following:
//openfile.php <?php
<?php $name = “file.txt”;
$fp = fopen($name, $mode); $mode = “r”;
if($fp){ $result = include(“openfile.php”);
echo “Could not open the file.”
if($result == 1) {
return 0;
} else
//continue reading/writing the file
return 1; }
?> ?>
Reading Assignment

File Input/Output in PHP


Classes in PHP

You might also like