PHP and Mysql: Tiji Thomas
PHP and Mysql: Tiji Thomas
Tiji Thomas
HOD
Department of Computer Applications
MACFAST
[email protected]
What is PHP?
<?php
?>
Example
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Comments in PHP
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
Variables in PHP
$var_name = value;
Assignment Operators
1. =
2. +=
3. -=
4. *=
5. /=
6. .=
7. %=
PHP Operators
Comparison Operators
1. ==
2. !=
3. >
4. <
5. >=
6. <=
Logical Operators
1. &&
2. ||
3. !
The Ternary Operator
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
?>
Strings in PHP
Example
<?php
$txt="Hello World";
echo $txt;
?>
The Concatenation Operator
The concatenation operator (.) is used to put two string values together.
Example:
<?php
$txt1=“Department :";
$txt2=“of Computer Applications , UC College";
echo $txt1 . " " . $txt2;
?>
1. strlen()
The strlen() function is used to find the length of a string
<?php
echo strlen("Hello world!");
?>
2. strpos()
<?php
?>
PHP Date()
Synatax:
date(format,timestamp)
Parameter Description
timestamp Optional. Specifies a timestamp. Default is the current date and time
(as a timestamp)
PHP Date - Format the Date
<?php
echo date("Y/m/d");
echo "<br />";
echo date("Y.m.d");
echo "<br />";
echo date("Y-m-d");
echo "<br />";
echo date("D-M-Y");
echo "<br />";
?>
Conditional Statements
The If...Else Statement
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false
Example -3
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>
The If...Else Statement
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
The If...Else Statement
html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
The Switch Statement
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example - Switch
<html>
<body>
<?php
$x = 1;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
PHP Arrays
$names = array(“Raju",“Rajan",“Ramu");
$names[0] = “Raju";
$names[1] = “Rajan";
$names[2] = “Ramu";
Example
<?php
$names[0] = “Raju";
$names[1] = “Meera";
$names[2] = “Ramu";
echo $names[1] . " and " . $names[2] .
" are ". $names[0] . "'s neighbors";
?>
Associative Arrays
Example -8
<?php
$ages["Rony"] = "32";
$ages['Tony'] = "30";
$ages['Sony'] = "34";
echo “Tony is " . $ages["Tony"] . " years old.";
?>
Multidimensional Arrays
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>
The do...while Statement
The do...while statement will execute a block of code at least once - it
then will repeat the loop as long as a condition is true.
do
{
code to be executed;
}
while (condition); <html>
<body>
<?php
$i=0;
do
{
Example-12 $i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
?>
</body>
</html>
For Statement
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>
Foreach Statement
foreach (array as value)
{
code to be executed;
}
<html>
<body>
<?php
Example-14 $arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>
Sorting an array
<?php
?>
PHP Functions
Creating PHP functions
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname ."<br />";
}
echo "My name is ";
writeMyName(“Thomas");
echo "My name is ";
writeMyName(“Varghese");
echo "My name is ";
writeMyName("Tom");
?>
</body>
</html>
Function return values
<html>
<body>
<?php
function add($x,$y)
{
Example-17
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Form Handling
<form>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
</form>
Checkboxes
Checkboxes are used when you want the user to select one
or more options of a limited number of choices.
Example-20
<form>
I have a bike:
<input type="checkbox" name="vehicle" value="Bike">
<br>
I have a car:
<input type="checkbox" name="vehicle" value="Car">
<br>
I have an airplane:
<input type="checkbox" name="vehicle" value="Airplane">
</form>
The Form's Action Attribute and the Submit Button
<body>
<form >
<select name="cars">
<option value="800"> Maruthi 800</option>
<option value="Alto">Maruthi ALTO</option>
<option value="Wagonor">Maruthi Wagonor</option>
<option value="Swift">Maruthi Swift</option>
</select>
</form>
</body>
</html>
PHP Form handling
The most important thing to notice when dealing with HTML forms and
PHP is that any form element in an HTML page will automatically be
available to your PHP scripts.
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html> Welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html
The $_GET Variable
The $_GET variable is an array of variable names and values sent by the
HTTP GET method.
The $_GET variable is used to collect values from a form with method="get".
Information sent from a form with the GET method is visible to everyone (it
will be displayed in the browser's address bar) and it has limits on the amount
of information to send (max. 100 characters).
You can insert the content of a file into a 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.
Example
<html>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
<html>
<body>
Menu.php <a href="default.php">Home</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>
</body>
</html>
w Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't
exist
a+
Read/Append. Preserves file content by writing to the end of the file
x
Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Reading a File Line by Line
Example-43
<?php
$file = fopen("Cinderella .txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
Create an Upload-File Form
To allow users to upload files from a form can be very useful.
Example 40
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
Filename:
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
• The enctype attribute of the <form> tag specifies which
content-type to use when submitting the form. "multipart/form-
data" is used when a form requires binary data, like the contents
of a file, to be uploaded
• The type="file" attribute of the <input> tag specifies that the
input should be processed as a file. For example, when viewed
in a browser, there will be a browse-button next to the input field
upload_file.php
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
By using the global PHP $_FILES array you can upload files from a
client computer to the remote server.
The first parameter is the form's input name and the second index
can be either "name", "type", "size", "tmp_name" or "error". Like
this:
• $_FILES["file"]["name"] - the name of the uploaded file
• $_FILES["file"]["type"] - the type of the uploaded file
• $_FILES["file"]["size"] - the size in bytes of the uploaded file
• $_FILES["file"]["tmp_name"] - the name of the temporary copy of
the file stored on the server
• $_FILES["file"]["error"] - the error code resulting from the file
upload
Saving the Uploaded File
<?php
setcookie("user", “UC College ", time()+3600);
?>
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
PHP Error Handling
When creating scripts and web applications, error handling is an
important part. If your code lacks error checking code, your
program may look very unprofessional and you may be open to
security risks.
Basic Error Handling: Using the die() function
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
PHP Filter?
A PHP filter is used to validate and filter data coming from
insecure sources.
<?php
$a = '[email protected]';
if ( filter_var('$a', FILTER_VALIDATE_EMAIL))
{
echo "Email is valid";
}
else
{
echo "Email is not valid";
}
var_dump($a);
?>
<?php
$no = 12.5;
var_dump(filter_var($no, FILTER_SANITIZE_NUMBER_INT));
?>
Validate Input
filter_input() function is using for validate input
<?php
1. CREATE DATABASE;
2. SHOW DATABASES;
3. USE database name;
4. CREATE TABLE
5. SHOW TABLES;
6. DESCRIBE table name;
7. DROP TABLE table name;
8. DROP DATABASE database name;
9. ALTER TABLE table name
11. SELECT
12 . DELETE FROM table name;
13 .TRUNCATE [TABLE] tbl_name
Connection to a MySQL Database
Syntax
mysql_connect(servername,username,password);
Parameter Description
mysql_close($con)
?>
Select Data From a Database Table
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mca2007", $con);
$result = mysql_query("SELECT * FROM Student");
while($row = mysql_fetch_array($result))
{
echo $row['Rollno'] . " " . $row['Name']. " " . $row['Mark'];
echo "<br />";
}
mysql_close($con);
?>
Display the Result in an HTML Table
Example Program
Delete
THANK YOU