0% found this document useful (0 votes)
48 views

PHP Coding

PHP is a server-side scripting language used to create dynamic web pages. To run PHP code, a server like XAMPP or VERTRIGO must be installed. PHP code is written within <?php ?> tags and saved with a .php file extension. Variables in PHP start with a $ sign and can hold different data types. PHP provides comparison, logical, and arithmetic operators to perform operations. Conditional statements like if/else are used to control program flow based on conditions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

PHP Coding

PHP is a server-side scripting language used to create dynamic web pages. To run PHP code, a server like XAMPP or VERTRIGO must be installed. PHP code is written within <?php ?> tags and saved with a .php file extension. Variables in PHP start with a $ sign and can hold different data types. PHP provides comparison, logical, and arithmetic operators to perform operations. Conditional statements like if/else are used to control program flow based on conditions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PHP

Before starting PHP


Since PHP is a server side scripting language, you have to install server software to run PHP code.

Plenty of server software are there on the internet, so you can type which server software you want use it.

In this lab manual we used VETRIGO server. We selected it because it contains application server and MYSQL database server together. Once you
have VERTRIGO installed on your computer, no need of installing additional database server. You can also use XAMP server, it is totally the same.

Introduction to PHP
✓ 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.
✓ This allows individual users to see customized Web pages.
✓ Web page visitors see the output from scripts, but not the scripts themselves.
Writing PHP code

✓ You 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
?>
✓ 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.

Other styles of PHP tag

o Short style
<?
Php statements
?>
To use this tag, you either need to enable short tags in your config file (short_open_tag = On), or compile PHP with short tags
enabled.
o ASP style
<%
Php statements
%>
It can be used if you have enabled the asp_tags configuration setting.
Running the first PHP code
To run, your PHP code must be placed inside the WWW folder of vertigo installation path.

You can find it inside: “Program Files/vertrigoServ/www”

First PHP code code #1


1 <?php
2 //Save the file with .php extension inside WWW folder.
Example "phpcode.php"
3 // Then open a browser and type localhost/hello.php or
127.0.0.1/phpcode.php
4 echo "Hello, World!";
5 ?>

PHP output statement


There are two output statements

✓ echo: has two formats


o echo output; Can accepts more than one outputs. echo output1, output2….;
o echo(output); Accepts only one output statement
✓ print: Also has two formats
o print output;
o print(output);
print statement accepts one argument only.
Unlike echo, print statement returns a value which represents whether the output statement succeeds.
PHP output statements code #2
1 <?php
2 echo "Output statement 1", "outpt statement 2";
3 print("Output statement 3");
4 ?>

Output of code #2

Working with variables


In PHP variables start with $ sign. This tells PHP that it is variable name.

To store a value in the variable use = sign as usual.

$name = ”John”;

PHP has a total of eight types: integers, doubles, Booleans, strings, arrays, objects, NULL, and resources:

1. Integers are whole numbers, without a decimal point, like 495.


2. Doubles are floating-point numbers, like 3.14159 or 49.0.
3. Booleans have only two possible values: TRUE and FALSE.
4. Strings are sequences of characters, like “PHP is very interesting”.
5. Arrays are named and indexed collections of other values.
6. Objects are instances of programmer-defined classes.
7. Resources are special variables that hold references to resources external to PHP such as database connections.
8. NULL is a special type that only has one value: NULL.
• PHP variable is loosely typed. A single variable may contain different type of data.
• In a variable you can store integer one time and string another time.
PHP variables code #3
1 <?php
2 echo"<h3>PHP variable</h3>";
3 $foo = 6;
4 echo $foo,"<br>";
5 $foo = "six";
6 echo $foo;
7 ?>
Output of code #3

Testing what type of data a variable contains.

• PHP provides built-in function to check the data in a variable


✓ is_integer($var): same as is_int($var)
✓ is_array($var2): Checks to see if $var2 is an array
✓ is_float($number): Checks if $number is a floating point number
✓ is_null($var1): Checks to see if $var1 is equal to 0
✓ is_numeric($string): Checks to see if $string is a numeric string
✓ is_string($string): Checks to see if $string is a string
✓ is_bool($var): finds out whether a variable is a boolean

PHP variables code #4


1 <?php
2 $foo = 6;
3 if(is_int($foo)){
4 print("foo contains integer");
5 }
6 ?>
Output of code #4
Type casting

In programming, type casting refers to converting a variable from one data type to another.

Implicit: Automatic conversion of type from one to another.

Explicit: Using casting functions to convert one type to another. The are two methods for explicit type conversion.

• settype ( variable, string type)


• Using cast methods

The cast methods are:

• (int), (integer) - cast to integer


• (bool), (boolean) - cast to boolean
• (float), (double), (real) - cast to float
• (string) - cast to string
• (array) - cast to array
• (object) - cast to object

PHP type casting code #5


1 <?php
2 $foo = "54"+12; //string 54 is converted into integer 54
(implicit casting)
3 echo gettype($foo), " ",$foo,"<br>";
4 $foo = (string)$foo;
5 echo "foo is ", gettype($foo), " ",$foo,"<br>";
6 settype($foo, "double");
7 echo "foo is ", gettype($foo), " ",$foo; Output of code #5
8 ?>
Using Operators

Operators in php are more similar like operators in other programming languages

Athematic operators
PHP athematic operators code #6 PHP pre and post -increment and decrement operators code #7
1 <?php 1 <?php
2 $num1 = 5; 2 $num1 = 5;
3 $num2 = 10; 4 echo $num++; // post-increment (5)
4 echo $num1 - $num2; // subtraction (-5) 5 echo ++$num; //pre-increment (7)
5 echo $num1 + $num2; //Addition (15) 6 echo --$num ; //pre-decrement (6)
6 echo $num1 * $num2; // multiplication (50) 7 echo $num--;//post-decrement (6)
7 echo $num1 / $num2;//division (0.5) 8 echo $num1; (5)
8 echo $num1 . $num2;// concatenation (510) 9 ?>
9 ?>

PHP comparison operators code #8 PHP logical operators code #9


1 <?php 1 <?php
2 $num1 = 5; 2 $num1 = false;
3 $num2 =”5”; 3 $num2 = true;
4 echo $num1==$num2;// equal (1/ True) 4 echo $num1 and $num2; // and operator (0/” ”/ False)
5 echo $num1===$num2;// identical (0/” ”/ False) 5 echo $num1 or num2;// or operator (1/True)
6 echo $num1<$num2;// less than (1/True) 6 echo $num1 xor $num2;// XOR operator (1/True)
7 echo $num1>$num2;//greater than (0/” ”/Flase) 7 echo !$num2; //Negation operator (1/True)
8 echo $num1!=$num2;//not equal (0/” ”/False) 8 ?>
9 ?>
Conditional Statements
PHP if else statement code #11
PHP if statement code #10
1 <?php
1 <?php
2 $num1 = 5;
2 $num1 = 5;
3 $num2 =”5”;
3 $num2 =”5”;
4 if($num1 == $num2)
4 if($num1 == $num2){
5 echo”num1 and num2 re equal”;
5 echo”num1 and num2 re equal”;
6 else
6 }
7 Echo “num1 and num2 are not equal”;
7 if($num1 === $num2 ){
8 if($num1 === $num2 )
8 echo “num1 and num2 are identical”;
9 echo “num1 and num2 are identical”;
9 }
10 else
10 ?>
11 echo “num1 and num2 are not identical”
12 ?>

PHP if else if… else statement code #12 PHP switch statement code #13
1 <?php 1 <?php
2 $num1 = 5; 2 $num = 3;
3 $num2 =”5”; 4 Switch($num1){
4 if($num1 > $num2) 5 Case 1:
5 echo”num1 is greater than num2”; 6 echo”One”; break;
6 else if($num2>$num1) 7 Case 2:
7 echo “num2 is greater than num2”; 8 echo”Two”;break;
8 else 9 Case 3:
9 echo “num1 and num2 are both equal”; 10 echo “Three”; break;
10 ?> 11 ?>
Loop statements
PHP for statement code #14 PHP while statement code #15
1 <?php 1 <?php
2 for($i = 1; $i<=5;$++){ 2 $i=1;
3 echo $i; 3 while($i<=5) {
4 } 4 echo $i; $i++;
5 }

PHP while statement code #16 PHP nested if statement code #17
1 <?php 1 <?php
2 $i=1; 2 echo”<table border=’1’>”;
3 Do { 3 for($i=1; $i<5; $i++){
4 echo $i; $i++; 4 echo”<tr>”;
5 } while($i<=5) 5 for($j=0;$j<5;$j++){
6 echo “<td>”+($i*$j)+”</td>”;
7 }
8 echo”</tr>”;
9 }
PHP array 10 echo”</table>”;

PHP creating indexed array way 1 code #18 PHP creating indexed array way 2 code #19
1 <?php 1 <?php
2 $product[0] = “Orange”; 2 $product = array(“Orange”, “Avocado”, “Banana”);
3 $product[1] = ”Avocado”; 3 print_r($product);
4 $product[2] = “Banana”; 4 ?>
5 // printing array
6 var_dump($product);
7 ?>
PHP creating associative array way 1 code #20 PHP creating associative array way 2 code #21
1 <?php 1 <?php
2 $product[“p1”] = “Orange”; 2 $product = array(“p1”=>”Orange”, “p2”=>”Avocado”,
3 $product[“p2”] = ”Avocado”; “p3”=>”Banana”);
4 $product[“p3”] = “Banana”; 3 print_r($product);
5 // printing array 4 ?>
6 var_dump($product);
7 ?>

Go throw an array using loop


PHP Go throw indexed array code #22 PHP Go throw associative array code #23
1 <?php 1 <?php
2 $product[0] = “Orange”; 2 $product[“p1”] = “Orange”;
3 $product[1] = ”Avocado”; 3 $product[“p2”] = ”Avocado”;
4 $product[2] = “Banana”; 4 $product[“p3”] = “Banana”;
5 // use one of the looping statements eg. For loop. 5 // use special loop called foreach loop.
6 for($i = 0;$i<count($product); $i++) { 6 foreach($product as $index=>$value)
7 echo $product[$i] , ”<br>”; 7 echo $value, ”<br>”;
8 } 8 }
9 ?> 9 ?>
PHP functions code #24 PHP functions with parameters and return code #25
1 <?php 1 <?php
2 // use key-word function to create functions 2 function adder($num1, $num2){
3 function display(){ 3 $sum = $num1 + $num2;
4 echo “You called the function”; 4 return $sum;
5 } 5 }
6 // calling the function 6 // calling the function
7 display(); 7 echo adder(2,3);
8 ?> 8 ?>

HTML form processing


Creating HTML form code #26 Creating processor.php code #27
1 <html><head></head> 1 // save the file as processor.php
2 <body> 2 <?php
3 <form method = “POST” action=”processor.php”> 3 $first_name = $_POST[“fname”];
4 <input type=”text” name=”fname”> 4 $password = $_POST[“pass”];
5 <input type=”password” name=”pass”> 5 echo “First name ”,$first_name;
6 <input type=”submit” value=”Send”> 6 echo “Password”, $password’;
7 </form> 7 ?>
8 </body></html>
PHP database programming
Step 1: Select on PhpMyAdmin from vertigo Step 2: Enter root and vertrigo for username and
setting password, in the browser and click Go
Step 3: Click on databases, enter database name Step 5: Create a table inside your database by entering the name
(eg. SRS) and click on create. (eg. Students) and number of fields (eg. 3), then click on Go.

Step 6: Enter field names with their type and length, (if it is integer
ignore the length), then click save

Step 4: Click on the database you created from list


of databases.
Now, we are ready to access a table using a PHP code.
Database information
Location: localhost Database name: SRS

Username: root Table name: Students


Table fields: firstName, age, grade
Password: vertrigo

PHP database programming simple insert operation code #28 PHP database programming simple select operation code #29
1 <?php 1 <?php
2 $con = mysql_connect(‘localhost’, ‘root’, ‘vertrigo’); 2 $con = mysql_connect(‘localhost’, ‘root’, ‘vertrigo’);
3 mysql_select_db(‘’SRS’); 3 mysql_select_db(‘’SRS’);
4 $q = “insert into Students values(‘Abebe’, 22, ‘B’)”; 4 $q = “select * from Students”;
5 $result = mysql_query($q); 5 $result = mysql_query($q);
6 if(mysql_affected_rows($result) > 0) 6 while($row = mysql_fetch_array($result)){
7 echo “Inserted successfully”; 7 Echo $row[0], $row[1], $row[2], “<br>”;
8 else 8 }
9 echo “Not inserted”;
Inserting value into Table, from HTML from
Step 2 Writing php file to handle insertion code #31
Step 1 Creating HTML form code #30
// save the file as insert.php
1 <html><head></head>
2 <body> 1 <?php
2 $con = mysql_connect(‘localhost’, ‘root’, ‘vertrigo’);
3 <form method = “GET” action=”insert.php”>
3 mysql_select_db(‘’SRS’);
4 <input type=”text” name=”fname”>
4 // getting values from HTML form
5 <input type=”number” name=”age”>
6 <input type=”text” name=”grade”> 5 $fname = $_GET[“fname”];
6 $age = $_GET[“age”];
7 <input type = “submit” value=”insert”>
7 $grade = $_GET[“grade”];
8 </form>
8 $q = “insert into Students values(‘$fname’, $age, ‘$grade’)”;
9 </body></html>
9 $result = mysql_query($q);
10 if(mysql_affected_rows($result) > 0)
11 echo “Inserted successfully”;
12 else
13 echo “Not inserted”;

Update and delete operations


PHP database programming update operation code #33
PHP database programming delete operation code #32
1 <?php
1 <?php
2 $con = mysql_connect(‘localhost’, ‘root’, ‘vertrigo’);
2 $con = mysql_connect(‘localhost’, ‘root’, ‘vertrigo’);
3 mysql_select_db(‘’SRS’);
3 mysql_select_db(‘’SRS’);
4 $q = “update Students set grade=’A’ where fname=’Abebe’”;
4 $q = “delete from Students where grade=’C’”;
5 $result = mysql_query($q);
5 $result = mysql_query($q);
6 if(mysql_affected_rows($result) > 0)
6 if(mysql_affected_rows($result) > 0)
7 echo “Updated successfully”;
7 echo “Deleted successfully”;
8 else
8 else
9 echo “Not Updated”;
9 echo “Not Deleted”;
PHP file uploading

✓ Uploading multimedia files (image, audio, video,


documents, etc) Include enctype=”multipart/form-data” in
the form
✓ Use POST for the method
✓ Create a file input form element.
Step 1 Creating HTML form to upload file code #34 Step 2 Writing php file to handle file uploading code #35
1 <html><head></head> // save the file as upload.php
2 <body> 1 <?php
3 <form method = “POST” action=”upload.php” 2 // getting uploaded file information using $_FILES array
enctype=”multipart/form-data”> 3 $file_name = $_FILES[“my_file”][“name”];
<input type=”file” name=”my_file”> 4 $file_type = $_FILES[“my_file”][“type”];
7 <input type = “submit” value=”upload”> 5 $temp_path = $_FILES[“my_file”][“temp_name”];
8 </form> 6 $file_size = $_FILES[“my_file”][“size”];
9 </body></html> 7 // moving a file from temporary directory to permanent directory
8 move_uploaded_file($temp_path, “myFiles/”.$file_name);
9 echo” File uploaded successfully”;
Create a folder to put uploaded files. For example create a folder
inside www , ”myFiles”.

You might also like