CH 5
CH 5
CH 5
Chapter Five
part
By Tesfahun
I
Outline
❖ Basic PHP Syntax
❖ Variables in PHP
session tracking
why we learn PHP
✓PHP runs on various platforms (Windows, Linux,
✓ To control user-access
✓ To encrypt data
Basic PHP Syntax
✓A PHP script can be placed anywhere in the
document.
<?php
// PHP code goes here
?>
Output Variables in PHP
❖The PHP echo statement is often used to output
data to the screen.
<?php
echo “well came to study 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
✓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;
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.
❖It's a good programming practice to close all files after
you have finished with them.
❖ The feof() function is useful for looping through data of unknown length.
❖ The example below reads the “test.txt" file line by line, until end-of-file
is reached:
❖ Example
<?php
$myfile = fopen(“test.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile))
{
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character - fgetc()
❖ The fgetc() function is used to read a single character from a file.
Example
<?php
$myfile = fopen(“test.txt", "r") or
die("Unable to open file!");
// Output one character until end-of-
file while(!feof($myfile))
{
echo fgetc($myfile);
}
fclose($myfile);
?>
PHP Write file append
❖Appending a File:- is a process that involves adding new data
elements to an existing file
<?php
$fp = fopen('f.txt', 'a');//opens file in append mode
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.
$f = "f.txt";
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");
echo "Dir name: $pathinfo[dirname]<br />\n";
echo "Base name: $pathinfo[basename] <br />\n";
echo "Extension: $pathinfo[extension] <br />\n";
?>
Output
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
setcookie(cookie_name, cookie_value,
[expiry_time], [cookie_path], [domain], [secure],
[httponly]);
?>
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.
<?php
session_destroy(); //destroy entire session
?>
PHP MySQL Database
❖ With PHP, you can connect to and manipulate databases.
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
❖Before we can access data in the MySQL
database, we need to be able to connect to the
server:
Syntax:
mysql_close(resource $link_identifier);
➢ If a resource is not specified then last opened database is
closed.
{
echo "Failed to connect to MySQL: " . $mysqli -
> connect_error;
exit();
}
$conn -> close();
Creating Database Connection in PHP OOP
• The CREATE DATABASE statement is used to create a database
in MySQL.
// Create database
$sql = "CREATE DATABASE wku";
if ($conn->query($sql) === TRUE)
{
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
Example (MySQLi Procedural)
// Create database
$sql = "CREATE DATABASE wku";
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
}
else {
echo "Error creating database: " .
mysqli_error($conn);
}
Drop Database using PHP Script
Note:- While deleting a database using PHP script, it does not
prompt you for any confirmation. So be careful while deleting a
MySql database.
Syntax
$sql = 'DROP DATABASE wku’;
$qury = $mysqli->query ($conn, $sql );
if(! $qury )
{
die('Could not delete database: ' . mysqli_error());
}
81
Selecting MySQL Database Using PHP Script
❖Once you get connection with MySQL server, it is required
to select a particular database to work with.
82
Cont..
Syntax:
mysql_select_db(db_name, connection);
Where
✓ db_name:-Required - MySQL Database name to be
selected
<?php
include connection.php’;
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully’;
mysqli_select_db( ‘wku’ );//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 wku created successfully";
}
else
{
echo "Error creating table: " .
mysqli_error($conn);
}
dropping table (reading assignment )
</form>
Cont..
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = “wku";
$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(‘wku');
$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"; 97
mysql_close($conn);
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(‘wku'); 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