CH 5
CH 5
CH 5
Variables in PHP
session tracking
why we learn PHP
PHP runs on various platforms (Windows, Linux,
It able create, open, read, write, delete, and close files on
the server
<?php
// PHP code goes here
?>
Output Variables in PHP
The PHP echo statement is often used to output data to the
screen.
print "Hello world!<br>";
?>
example
<?php
?>
PHP comments
<?php
// This is a single-line comment
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
if (condition)
{
code to be executed if condition is true;
}
example
<?php
$x = 5;
?>
PHP - The if...else Statement
The if...else statement executes some code if a condition is
true and another code if that condition is false.
Syntax
if (condition) {
} else {
}
example
<?php
$x = 5;
if ($x < "10") {
echo “the number is less than 10!";
}
else {
echo “the number is less than 5!";
}
?>
The PHP switch Statement
Use the switch statement to select one of many blocks of code
to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from all labels;
}
example
<?php
$color = “yellow";
switch ($color) {
case “pink":
echo "Your favorite color is pink!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
In PHP, we have the following loop types:
Syntax
while (condition) {
code to be executed;
}
example
<?php
$num=1;
while($num<=5)
echo $num;
$num++;
?>
The PHP do...while Loop
do {
code to be executed;
Syntax
}
example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used
to loop through each key/value pair in an array.
Syntax
code to be executed;
}
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
PHP Arrays
An array stores multiple values in one single
variable
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";
?>
types of array
indexed
Associative
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
);
?>
PHP function
Syntax
function functionName()
{
code to be executed;
}
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
PHP Form Processing
Controls used in forms: Form processing contains
a set of controls through which the client and
server can communicate and share information.
fopen(filename, mode)
Set By:-Tesfahun N. 40
PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the
string into file.
example
<?php
fclose( $file );
?>
FILE_EXISTS() FUNCTION
If you try to open a file that doesn't exist, PHP will
generate a warning message.
To avoid these error messages you should always
implement PHP file_exists() function.
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file))
{ // Attempt to open the file
$handle = fopen($file, "r");
}
else
{ echo "ERROR: File does not exist."; }
?>
PHP Close File - fclose()
The fclose() function is used to close an open file.
<?php
fclose($fp);
?>
File Attributes
File Size:-The function filesize() retrieves the
size of the file in bytes.
EXAMPLE
<?php
$f = "C:\Windows\win.ini";
$size = filesize($f);
echo $f . " is " . $size . " bytes.";
?>
When executed, the example code displays:
C:\Windows\win.ini is 92 bytes.
Set By:-Tesfahun N. 48
File History
To determine when a file was
last accessed=> fileatime()
modified=>filemtime(),
Changed =>filectime().,
<?php
$dateFormat = "D d M Y g:i A";
$f = "C:\Windows\win.ini";
$atime = fileatime($f);
$mtime = filemtime($f);
$ctime = filectime($f);
echo $f . " was accessed on " . date($dateFormat, $atime) . ".<br>";
echo $f . " was modified on " . date($dateFormat, $mtime) . ".<br>";
echo $f . " was changed on " . date($dateFormat, $ctime) . ".";
?>
Set By:-Tesfahun N. 49
File Permissions
Before working with a file you may want to check whether it is
readable or writeable to the process.
<?php
$f = "f.txt";
?>
Set By:-Tesfahun N. 50
Working with CSV Files
Set By:-Tesfahun N. 51
Reading of csv files
<?php
$f="stud.csv";
$fi = fopen($f, "r");
while ($record = fgetcsv($fi))
{
foreach($record as $field)
{
echo $field . "<br>";
}
}
fclose($f);
?>
Set By:-Tesfahun N. 52
Directories
The directory functions allow you to retrieve
information about directories and their contents.
Set By:-Tesfahun N. 53
Example
<?php
$pathinfo= pathinfo("C:/xampp/htdocs/ip/f.txt");
Set By:-Tesfahun N. 54
Part II
.....
Objective
PHP Cookies and Session
Once a cookie has been set, all page requests that follow
return the cookie name and value.
A cookie can only be read from the domain that it has been
issued from.
Creating Cookies
Let’s now look at the basic syntax used to create a cookie.
<?php
?>
Cont..
Php“setcookie” is the PHP function used to create the cookie.
“cookie_name” is the name of the cookie that the server will use
when retrieving its value from the $_COOKIE array variable. It’s
mandatory.
<?php
setcookie("user_name", "Guru99", time() - 360,'/');
?>
What is a Session?
A session is a global variable stored on the server.
If the client browser does not support cookies, the unique php
session id is displayed in the URL
Cont..
Sessions have the capacity to store relatively larger than
cookies.
If you want to destroy only a session single item, you use
the unset() function.
1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO
Steps to access MySQL database from PHP page
1. Create connection
2. Select a database to use
3. Send query to the database
4. Retrieve the result of the query
5. Close the connection
Create Connection to MySQL server
1. MySQLi Object-Oriented
2. MySQLi Procedural
3. PHP Data Objects (PDO)
MySQLi Object-Oriented
<?php
$servername = "localhost";
$un = "root";
$pass = "";
// Create connection
$conn = new mysqli($servername, $un, $pass);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$sn = "localhost";
$un = "root";
$pas = "";
// Create connection
$conn = mysqli_connect($sn, $un, $pas);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully by using pros";
?>
Example (PDO)
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Closing a connection Using PHP Script
Syntax:
mysql_close(resource $link_identifier);
If a resource is not specified then last opened database is
closed.
This function returns true if it closes connection
successfully otherwise it returns false.
Clothing connection
<?php
$conn = new mysqli("localhost",“un",“pas“)
if ($mysqli -> connect_error)
{
echo "Failed to connect to MySQL: " . $mysqli ->
connect_error;
exit();
}
$conn -> close();
?>
Creating Database Connection in PHP OOP
Syntax
$sql = 'DROP DATABASE Bit’;
$qury = $mysqli->query ($conn, $sql );
if(! $qury )
{
die('Could not delete database: ' . mysqli_error());
}
81
Selecting MySQL Database Using PHP Script
82
Cont..
Syntax:
mysql_select_db(db_name, connection);
Where
db_name:-Required - MySQL Database name to be
selected
Connection:-Optional - if not specified then last opened
connection by mysql_connect will be used.
Example
<?php
include connection.php’;
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully’;
mysqli_select_db( ‘Bit’ );//data base is selected
84
mysqli_close($conn);
?>
Creating table
Create a MySQL Table Using MySQLi
and PDO
if (mysqli_query($conn, $sql)) {
echo "Table Bit created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($conn);
}
dropping table (reading assignment )
</form>
Cont..
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = “Bit";
$con = mysqli_connect($server, $username, $password);
if(!$con){
echo "Error : ".mysqli_error();
return;
}
$db = mysqli_select_db($database,$con);
if(!$db)
{echo "Error : ".mysqli_error();
return;}
?>
Cont.
<?php
if(isset($_POST['submit']))
$name = $_POST["name"];
$age = $_POST["age"];
?>
Getting Data From MySql Database
Data can be fetched from MySQL tables by executing SQL SELECT statement through
mysql_query() returns a result set of the query if the SQL statement is SELECT
just like mysql_fetch_row() and an associative array, with the names of the fields
as the keys.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, salary FROM employee';
mysql_select_db(‘Bit');
$result = mysql_query( $sql, $conn );
96
Getting Data From MySql Database: Example
if(! $ result )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo “id:{$row[‘id']} <br> ".
“name: {$row[‘name']} <br> ".
“salary: {$row['salary']} <br> ".
"------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
97
?>
Getting Data From MySql Database: Example
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, salary FROM employee';
mysql_select_db(‘Bit'); 99
if(! $result )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
echo "EMP ID :{$row[‘id']} <br> ".
"EMP NAME : {$row[‘name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
100
Getting Data From MySql Database: Example
<?php
include(“conn.php");
mysql_select_db(“MyDB”,$conn);
$sql=“select * from employee”;
$result = mysql_query($sql,$conn);
If(!$result)
die(“Unable to query:”.mysql_err());
while($row=mysql_fetch_row($result)){
for($i=0;$i<count($row);$i++)
print “$row[$i]”;
print”<br>”;
}
mysql_close($link);
?>
Reading Assignment
When the individual objects are created, they inherit all the
properties and behaviors from the class, but each object will have
different values for the properties.
?>
• Example