Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

1

CHAPTER FIVE
Basics of PHP

Mulugeta G..
2

Introduction
• PHP stands for Hypertext Preprocessor

• PHP is a powerful server-side scripting language for creating

dynamic and interactive websites.

• PHP is appropriate for Web development and can be embedded

directly into the HTML code.

• PHP is often used together with Apache(web server) on various

operating systems.

• A PHP file may contain text, HTML tags and scripts.


3

Introduction
• PHP files are returned to the browser as plain HTML

• PHP files have a file extension of “.php”

• PHP is case sensitive:

• [$color, $COLOR, and $coLOR are different]

• PHP supports many databases (MySQL, Informix, Oracle,

MariaDB, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)


4

What can PHP do


• PHP can generate dynamic page content

• PHP can create, open, read, write, delete, and close files on the server

• PHP can collect form data, send and receive cookies

• PHP can add, delete, modify data in your database

• PHP can be used to control user-access and encrypt data

• With PHP you are not limited to output HTML.

• You can output images, PDF files, and even Flash movies.

• You can also output any text, such as XHTML and XML.
5

Basic PHP Syntax


• A PHP scripting block can be placed anywhere in the document.

• Syntax:

<?php

// PHP code goes here

?>

• Each code line in PHP must end with a semicolon.


6

Output statements
• Two basic statements to output text with PHP: echo and print.
Echo Format Print Format
echo output1, output2, output3, output4 print output;

echo (output); print (output);

• Unlike echo print can accept only one argument.

• It is possible to embed html tags into echo and print statement.


<?php
• Example:
echo "Hello <br> World";

?>
7

Comments
• Is a line that is not read/executed as part of the program.

• There are two commenting formats in PHP:

• Single-line: to make a single-line comment ( // )

• Multi-lines: to make a multiple line comment block (/* and */ )

<?php
// This is a single-line comment
/*
This is a
multiple line comment
block in Php
*/
?>
8

Variables
• Variables are used for storing values, such as numbers, strings or function

results.

• All variables in PHP start with a $ dollar sign symbol.

• The correct way of setting a variable in PHP:

• $var_name = value;

• $txt = "Hello World!";

• In PHP a variable does not need to be declared before being set.

• In PHP the variable is declared automatically when you use it.

• The variable name is case-sensitive.


9

Variables
• PHP automatically converts the variable to the correct data type,

depending on their value.

• A variable name must start with a letter or an underscore.

• A variable name can consist of numbers, letters, underscores but you

cannot use characters like + , - , % , ( , ) . & , etc

• A variable name should not contain spaces.

• A variable name cannot start with a number

• If a variable name is more than one word, it should be separated with

underscore ($my_string), or with capitalization ($myString)


10

Data types
• Boolean (bool or boolean)

• Simplest of all

• Can be either TRUE or FALSE

• Integer (int or integer)

• Hold integer values

• Floating point (float or double or real)

• Hold floating point values

• String (string)

• Hold strings of characters within either single quote (‘) or double quote (‘’)

• Escaping of special characters can be done using \

• Ex. “this is a string”, ‘this is another string’, “yet \”another\” one”


11

Data types
• Array

• Collection of values of the same data type

• NULL

• Represents that a variable has no value

• A variable is considered to be NULL if

• it has been assigned the constant NULL.

• it has not been set to any value yet.

• it has been unset()


12

Strings
• Strings: are sequences of characters within single or double quotes
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
$literally = "My $variable will print!\n";
print($literally);
?>
• This will produce following result:
My $variable will not print!
My name will print
• There are no limits on string length
13

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 name is case-sensitive.

• By convention, constant identifiers are always uppercase.

• A constant name starts with a letter or underscore (can be a

combination of letters, numbers, or underscores.)

• If you have defined a constant, it can never be changed or

undefined.
14

Constants
• To define a constant you have to use define() function

• There is no need to write a dollar sign ($) before a constant.

• To retrieve the value of a constant, you can simply specifying its


name.
• You can also use the function constant() to read a constant's value
• Example:
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
15

Operator Types
• What is Operator?

• For example in the expression 4 + 5 = 9.

• Here 4 and 5 are called operands and + is called operator.

• PHP language supports following type of operators.

• Arithmetic Operators: [ +, -, *, /, %, ++, --]

• Comparison Operators: [ ==, !=, >, <, >=, <= ]

• Logical (or Relational) Operators: [ &&, ||, ! ]

• Assignment Operators : [ =, +=, -=, *=, %= ]

• Conditional (or ternary) Operators: [ ? : ]

• Example: If Condition is true ? Then value X : Otherwise value Y


16

Control Statements
• You can use conditional statements in your code to make your

decisions based on the different condition.

• PHP supports following decision making statements:

• if...else statement - use this statement if you want to execute a set

of code when a condition is true or if the condition is false

• If else if statement - is used with the if...else statement to execute a

set of code if one of several condition are true.

• switch statement - is used if you want to select one of many

blocks of code to be executed.


17

Example
<?php <?php
$t = date("H"); $t = date("H");
if ($t < "20") { echo "<p>The hour (of the server)
echo "Have a good day!"; is " . $t;
} echo ", and will give the following
?> message:</p>";
_______________________
<?php if ($t < "10") {
$t = date("H");
echo "Have a good morning!";
if ($t < "20") { } elseif ($t < "20") {
echo "Have a good day!"; echo "Have a good day!";
} else { } else {
echo "Have a good night!"; echo "Have a good night!";
}
?> }
?>
18

Example
<?php <html>
$favcolor = "red"; <body>
switch ($favcolor) {
case "red": <?php
echo "Your favorite color is function myTest() {
red!"; static $x = 0;
break; echo $x;
case "blue":
echo "Your favorite color is $x++;
blue!"; }
break; myTest();
case "green": echo "<br>";
echo "Your favorite color is myTest();
green!";
break; echo "<br>";
default: myTest();
echo "Your favorite color is ?>
neither red, blue, nor green!";
} </body>
?>
</html>
19

Control Statements
• Instead of adding several almost equal code-lines in a script, we can use

loops to perform a task like this.

• In PHP, we have the following looping statements:

• while - loops through a block of code as long as the specified condition is

true

• do...while - loops through a block of code once, and then repeats the loop as

long as the specified condition is true

• for - loops through a block of code a specified number of times

• foreach - loops through a block of code for each element in an array


20

Example
<?php <?php
$x = 1; for ($x = 0; $x <= 10; $x++)
{
while($x <= 5) { echo "The number is: $x <br>";
echo "The number is: $x <br>"; }
$x++; ?>
}
?> ________________________
____________________________ <?php
<?php $colors = array("red", "green",
$x = 1; "blue", "yellow");
do { foreach ($colors as $value) {
echo "The number is: $x <br>"; echo "$value <br>";
$x++; }
} while ($x <= 5);
?> ?>
21

String Operation
String Concatenation Operator
• To concatenate two string variables together, use the dot (.) operator.

<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
• This will produce following result:

Hello World 1234


22

Using the strlen() function


• The strlen() function is used to find the length of a string.

• Let's find the length of our string "Hello world!":

<?php

echo strlen("Hello world!");

?>

• This will produce following result: 12

• The length of a string is often used in loops or other functions,

when it is important to know when the string ends.


23

Using the strpos() function


• The strpos() function is 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.
• Example lets find the string "world" in Hello world string:
<?php
echo strpos("Hello world!","world");
?>
• This will produce following result: 6
• As you see 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.
24

PHP String Function


• Get The Length of a String ----- strlen()

• Count The Number of Words in a String ------ str_word_count()

• Reverse a String ----- strrev()

• Search For a Specific Text Within a String ------ strpos()

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
• Replace Text Within a String ------ str_replace()

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
25

THANK YOU
Part II
26

PHP Functions
• is a block of code that can be executed whenever we need it.

Creating PHP functions

• All functions start with the word "function()"

• Name the function

• The name can start with a letter or underscore (not a number)

• Syntax:
function function_Name()
{
// block of code
}
27

Example
A simple function that writes a name when it is called:
<html>
<body>
<?php
function writeMyName()
{
echo “abebe belachewu";
}
writeMyName();
?>
</body>
</html>
28

PHP Functions with Parameters


• PHP gives you option to pass your parameters inside a function.

• You can pass any number of parameters your like.

• These parameters work like variables inside your function.

• Example: two integer parameters and add them together and then print them.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
29

Example
<html>
<body>
<?php
function writeMyName($fname)
{
echo “$fname <br />";
}
echo "My name is ";
writeMyName(“abebe");
?>
</body>
</html>
30

PHP Forms and User Input


• The PHP $_GET and $_POST variables are used to retrieve

information from forms, like user input.

• The most important thing to notice when dealing with HTML forms

and PHP is that any form element in HTML page will automatically
be available to your PHP scripts.
Form example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
31

PHP Forms and User Input


• The HTML contains two input fields and a submit button.
• When the user fills in this form and click on the submit button,
the form data is sent to the "welcome.php" file.
• The "welcome.php" file looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Welcome John.
You are 28 years old.
32

PHP $_GET
• The $_GET variable is used to collect values from a form with
method="get".
• The $_GET variable is an array of variable names and values
are sent by the HTTP GET method.
Example
<form action="welcome.php" method="get">

Name: <input type="text" name="name" />

Age: <input type="text" name="age" />

<input type="submit" />

</form>
33

PHP $_GET
• When the user clicks the "Submit" button, the URL
sent could look something like this:
localhost/welcome.php?name=Peter&age=37
• The "welcome.php" file can now use the $_GET variable to
catch the form data
• Note that the names of the form fields will automatically be the
ID keys in the $_GET array:
Welcome <?php echo $_GET["name"]; ?>.<br />

You are <?php echo $_GET["age"]; ?> years old!


34

Why use $_GET


• Information sent from a form with the GET method is visible

to everyone (it will be displayed in the browser's address bar)

• So this method should not be used when sending

passwords or other sensitive information!

• Get method has limits on the amount of information to send

• The value cannot exceed100 characters.

• So it is not suitable on large variable values.


35

PHP $_POST
• The $_POST variable is used to collect values from a form

with method="post".

• The $_POST variable is an array of variable names and values

are sent by the HTTP POST method.

• Information sent from a form with the POST method is

invisible to others and has no limits on the amount of


information to send.
36

Example
<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>

• When the user clicks the "Submit" button, the URL will not
contain any form data, and will look something like this:
localhost/welcome.php
37

The $-REQUEST Variable

• The PHP $_REQUEST variable contains the contents of both

$_GET and $_POST variables.

• The PHP $_REQUEST variable can be used to get the result

from form data sent with both the GET and POST methods.

• Example

Welcome <?php echo $_REQUEST["name"]; ?>.<br />

You are <?php echo $_REQUEST["age"]; ?> years old!


38

PHP Include File


• You can insert the content of one PHP file into another PHP file

before the server executes it, with the include( ) or require( )


function.

• 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


39

PHP Include File


• These two functions are used to create functions, headers,

footers, or elements that will be reused on multiple pages.

• This means that you can create a standard header, footer, or

menu file for all your web pages.

• When the header needs to be updated, you can only update the

include file, or when you add a new page to your site, you can
simply change the menu file (instead of updating the links on all
your web pages).
40

PHP include( ) Function


• The include() function takes all the content in a specified file
and includes it in the current file.
• If an error occurs, the include() function generates a warning,
but the script will continue execution.
Save the file as header.php
<a href="default.php">Home</a>
<a href="tutorials.php">Tutorials</a>
Save the file as main.php
<a href="examples.php">Examples</a>
<a href="about.php">About Us</a> <?php include(‘header.php’); ?>
<a href="contact.php">Contact Us</a> <hr>
<hr> <p> add some contents </p>
<p> add some contents here</p>
41

PHP require( ) Function


• The require() function is identical to include(), except that it handles

errors differently.

• The require() generates a fatal error, and the script will stop.

<?php require(‘header1.php’); ?>


<hr>
<p> add some contents here </p>

• The script execution stopped after the fatal error.

• It is recommended to use the require() function instead of include(),

because scripts should not continue after an error.


42

PHP Cookies
• A cookie is 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.

• A cookie is created with the setcookie() function.


43

PHP Sessions
• 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 last until the user closes the browser.

• Session variables hold information about one single user, and are

available to all pages in one application.

• A session is started with the session_start() function.

• Session variables are set with the PHP global variable: $_SESSION.
44

PHP Cookies Vs Sessions


45

PHP MySQL
• MySQL is the most popular open-source database system.

• The data in MySQL is stored in database objects called tables.

• A table is a collection of related data entries and it consists of

columns and rows.

• Databases are useful when storing information categorically.


• Example: Create a Database Called iplab
• Create a table called account
id name username password usertype
1 Daniel Daniel dani123 Admin
2 Meri Meri meri123 Manager
46

PHP MySQL Connection to Database


• Before you can access data in a database, you must create a
connection to the database.
• In PHP, this is done with the mysqli_connect() function.
• Syntax
mysqli_connect( servername, username, password);

Parameter Description
servername Optional. Specifies the server to connect to.
Default value is "localhost:3306"
username Optional. Specifies the username to log in with.
Default value is the name of the user that owns the server
password Optional. Specifies the password to log in with.
Default is ""
47

Example
• Lets store the connection in a variable ($con) for later use in the
script.
• The "die" part will be executed if the connection fails:

<?php
$con = mysqli_connect(“host",“username",“password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code

mysqli_close($con);

?>
48

Example
• index.php
<fieldset>
<legend> Information </legend>
<form action="insert.php" method="post">
Name:<input type="text" name="name" required>
<p></p>
Category: <input type="text" name="category" required>
<p></p>
<input type="submit" name="submit" value="Add Student">
</form>
</fieldset>
49

Example
• dbcon.php
<?php
$host="localhost";
$username="root";
$password="";
$dbname="kana";

$con=mysqli_connect($host,$username,$password) or die
("DB Not Connected!");
mysqli_select_db($con,$dbname) or die("DB Not Selected!");

?>
50

Example
• insert.php
<?php
include('dbcon.php');

$name=$_POST['name'];
$category=$_POST['category'];

mysqli_query($con, "insert into account (name, category)


values ('$name','$category’) ") or die (mysqli_error());

header('location:index.php');
?>
51

Example
• Write a PHP code to register new user
52

Example
• Lets add a link that displays the detail information of the users
53

Example
• Develop a simple user registration system that authenticates
users to add new users.
54

Project Title
1. Exit Exam Management System

2. Hotel Management System

3. Movie Ticket Booking System

4. Laboratory Equipment Management System

5. Student Information Management System

6. GYM management system

7. Blood bank and donor management system


55

?
END OF CHAPTER FIVE
Have a nice time

You might also like