PHP / MySQL
Dec 30, 2015
PHP / MySQL
What is PHP?
PHP is an acronym for "PHP Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP costs nothing, it is free to download and use
What is a PHP File?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain HTML
PHP files have extension ".php"
What Can PHP Do?
PHP can generate dynamic page content
PHP can create, open, read, write, and close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can restrict users to access some pages on your website
PHP can encrypt data
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
What Do I Need?
To start using PHP, you can:
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then install PHP and MySQL
Use a Web Host With PHP Support
If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:
install a web server
install PHP
install a database, such as MySQL
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php// PHP code goes here?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
PHP Case Sensitivity
In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are case-insensitive.
However; in PHP, all variables are case-sensitive.
Much Like Algebra
x=5y=6z=x+y
In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
In PHP these letters are called variables.
PHP Variables
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for PHP variables:A variable starts with the $ sign, followed by the name of the variableA variable name must start with a letter or the underscore characterA variable name cannot start with a numberA variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )Variable names are case sensitive ($y and $Y are two different variables)
Creating (Declaring) PHP Variables
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
<?php$txt="Hello world!";$x=5;$y=10.5;?>
PHP is a Loosely Type Language
notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.
PHP Variable Types
Integer: are whole numbers, without a decimal point, like 4195.
Double: are floating-point numbers, like 3.14159 or 49.1
Boolean: have only two possible values either true or false.
NULL: is a special type that only has one value: NULL.
String: are sequences of characters, like ‘hello world'
Array: are named and indexed collections of other values.
Object: are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Resources: are special variables that hold references to resources external to PHP (such as database connections).
var_dump($x);
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local
global
static
PHP $GLOBALS (super global) variable
<?php
echo $_SERVER['PHP_SELF'];
echo $_SERVER['argv'];
echo $SERVER['GATEWAY_INTERFACE'];
echo $_SERVER['SERVER_ADDR'];
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['SERVER_SOFTWARE'];
echo $_SERVER['SERVER_PROTOCOL'];
echo $_SERVER['REQUEST_METHOD'];
echo $_SERVER['REQUEST_TIME'];
echo "The query string is: ".$_SERVER['QUERY_STRING'];
echo $_SERVER['HTTP_ACCEPT_CHARSET'];
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['HTTP_USER_AGENT'];
echo $_SERVER['REMOTE_ADDR'];
?>
PHP Constants
A constant value cannot change during the execution of the script. By default a constant is case-sensitiv. By convention, constant identifiers are always uppercase. A
constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
If you have defined a constant, it can never be changed or undefined.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE");
?>
Samples
<?phpecho strlen("Hello world!");echo strpos("Hello world!","world");
echo chr(97);
echo ord("a");
echo md5("hello");
echo trim(" test ");
echo strip_tags("mbn <br> ttt");?>
PHP echo and print Statements
There are some difference between echo and print:
echo - can output one or more strings
print - can only output one string, and returns always 1
Tip: echo is marginally faster compared to print as echo does not return any value.
PHP Arithmetic Operators
Operator Name Example Result
+Addition $x + $y Sum of $x and $y
-Subtraction $x - $y Difference of $x and $y
*Multiplication $x * $y Product of $x and $y
/Division $x / $y Quotient of $x and $y
%Modulus $x % $y Remainder of $x divided by $y
Example<?php$x=10; $y=6;echo ($x + $y); // outputs 16echo ($x - $y); // outputs 4echo ($x * $y); // outputs 60echo ($x / $y); // outputs 1.6666666666667 echo ($x % $y); // outputs 4 ?>
PHP Assignment Operators
Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
Example
<?php$x=10; echo $x; // outputs 10
$y=20; $y += 100;echo $y; // outputs 120
$z=50;$z -= 25;echo $z; // outputs 25
$i=5;$i *= 6;echo $i; // outputs 30
$j=10;$j /= 5;echo $j; // outputs 2
$k=15;$k %= 4;echo $k; // outputs 3?>
PHP String Operators
Example
<?php$a = "Hello";$b = $a . " world!";echo $b; // outputs Hello world!
$x="Hello";$x .= " world!";echo $x; // outputs Hello world! ?>
Operator Name Example Result
.Concatenation $txt1 = "Hello"
$txt2 = $txt1 ." world!"Now $txt2 contains "Hello world!"
.=Concatenation assignment $txt1 = "Hello"
$txt1 .= " world!"Now $txt1 contains "Hello world!"
PHP Increment / Decrement Operators
Example
<?php$x=10; echo ++$x; // outputs 11
$y=10; echo $y++; // outputs 10
$z=5;echo --$z; // outputs 4
$i=5;echo $i--; // outputs 5?>
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Comparison Operators
<?php$x=100; $y="100";var_dump($x == $y);echo "<br>";var_dump($x === $y);echo "<br>";var_dump($x != $y);echo "<br>";var_dump($x !== $y);echo "<br>";
?>
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y
<= Less than or equal to $x <= $y True if $x is less than or equal to $y
PHP Conditional Statementsif (condition) { code to be executed if condition is true; }
If (condition) { code to be executed if condition is true; }else { code to be executed if condition is false; }
if (condition) { code to be executed if condition is true; }elseif (condition) { code to be executed if condition is true; }else { code to be executed if condition is false; }
PHP Conditional Statementsswitch (n){case label1: code to be executed if n=label1; break;case label2: code to be executed if n=label2; break;case label3: code to be executed if n=label3; break;...default: code to be executed if n is different from all labels;}
<?php$favcolor="red";switch ($favcolor){case "red": echo "Your favorite color is red!"; break;case "blue": echo "Your favorite color is blue!"; break;case "green": echo "Your favorite color is green!"; break;default: echo "Your favorite color is neither red, blue, or green!";}?>
PHP Loopswhile (condition is true) { code to be executed; }
<?php $x=1; while($x<=5) { echo "The number is: $x <br>"; $x++; } ?>
PHP Loopsdo { code to be executed; }while (condition is true);
<?php $x=1; do { echo "The number is: $x <br>"; $x++; }while ($x<=5)?>
PHP Loopsfor (init counter ; test counter ; increment counter) { code to be executed; }
<?php for ($x=0; $x<=10; $x++) { echo "The number is: $x <br>"; } ?>
PHP Loopsforeach ($array as $value) { code to be executed; }
<?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; }?>
PHP Functions
User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
<?php
function functionName (){code to be executed;}
?>
PHP Functions
Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma.
<?php
function familyName($fname,$year){echo "$fname Refsnes. Born in $year <br>";}
familyName(“ali","1975");familyName(“hasan","1978");familyName(“reza","1983");?>
PHP Functions
Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:
<?php
function setHeight($minheight=50){echo "The height is : $minheight <br>";}
setHeight(350);setHeight(); // will use the default value of 50setHeight(135);setHeight(80);
?>
PHP Functions
Returning values
To let a function return a value, use the return statement:
<?php
function sum($x,$y){$z=$x+$y;return $z;}
echo "5 + 10 = " . sum(5,10) . "<br>";echo "7 + 13 = " . sum(7,13) . "<br>";echo "2 + 4 = " . sum(2,4);
?>
Local and Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
Local and Global Scope
The following example tests variables with local and global scope:
Example
<?php
$x=5; // global scope
functionmyTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
Local and Global Scope
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x=5;
$y=10;
functionmyTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
Local and Global Scope
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x=5;
$y=10;
functionmyTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
Local and Global Scope
PHP The global Keyword
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
Example
<?php
$x=5;
$y=10;
functionmyTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
Local and Global Scope
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
functionmyTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
PHP Arrays
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Volvo";$cars2="BMW";$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";?>
PHP Arrays
The count() Function
The count() function is used to return the length (the number of elements) of an array:
<?php
$cars=array("Volvo","BMW","Toyota");echo count($cars);?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop, like this:
<?php
$cars=array("Volvo","BMW","Toyota");$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo "<br>"; }?>
PHP Arrays
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
?>
or
<?php
$age['Peter']="35";$age['Ben']="37";$age['Joe']="43";
echo "Peter is " . $age['Peter'] . " years old.";?>
PHP Arrays
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; }?>
PHP Arrays
Sort Functions For Arrays
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
<?php
$numbers=array(4,6,2,22,11);sort($numbers);
$arrlength=count($numbers);for($x=0;$x<$arrlength;$x++) { echo $numbers[$x]; echo "<br>"; }
?>
Include Files
In PHP, you can insert the content of one PHP file into another PHP file before the server executes it.
The include and require statements are used to insert useful codes written in other files, in the flow of execution.
Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use include. Otherwise, in case of FrameWork, CMS or a complex PHP application coding, always use require to include a key file to the flow of execution. This will help avoid compromising your application's security and integrity, just in-case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.
<html><body>
<?php include 'header.php'; ?><h1>Welcome to my home page!</h1><p>Some text.</p>
</body></html>
File Upload<html><body><form action="upload_file.php" method="post“ enctype="multipart/form-data"><label for="file">Filename:</label><input type="file" name="file" id="file"><br><input type="submit" name="submit" value="Submit"></form></body></html>
<html><body><form action="upload_file.php" method="post“ enctype="multipart/form-data"><label for="file">Filename:</label><input type="file" name="file" id="file"><br><input type="submit" name="submit" value="Submit"></form></body></html>
Cookies
What is a Cookie?
A cookie is often 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. With PHP, you can both create and retrieve cookie values.
Syntax
setcookie(name, value, expire, path, domain);
<?phpsetcookie("username", “ali", time()+60*60*24*30);?>
<?phpif (isset($_COOKIE["username"])) echo "Welcome " . $_COOKIE["user"] . "!<br>";else echo "Welcome guest!<br>";?>
<?php// set the expiration date to one hour agosetcookie("user", "", time()-3600);?>
How to Retrieve a Cookie Value?
How to Delete a Cookie?
SessionsA PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag
<?phpsession_start();if(isset($_SESSION['views']))$_SESSION['views']=$_SESSION['views']+1;else$_SESSION['views']=1;echo "Views=". $_SESSION['views'];?>
<?phpsession_start();if(isset($_SESSION['views'])) unset($_SESSION['views']);?>
You can also completely destroy the session by calling the session_destroy() function:
<?phpsession_destroy();?>
Destroying a Session
mail() Function
Parameter Description
to Required. Specifies the recipient's email address(es)
subject Required. Specifies the email's subject line. Note: This parameter cannot contain any newline characters
message Required. Specifies the actual email body (the message to be sent). Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers such as "From", "Cc", "Bcc", etc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies any additional parameters
Syntax
mail(to,subject,message,headers,parameters)
PHP & Database
Connect to the MySQL Server
Before we can access data in a database, we must open a connection to the MySQL server.
In PHP, this is done with the mysqli_connect() function.
Syntax
mysqli_connect(host,username,password,dbname);
<?php$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
mysqli_close($con);?>
PHP & Database
Insert Data Into a Database Table
The INSERT INTO statement is used to add new records to a database table.
Syntax
INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)
<?php$con=mysqli_connect("example.com","peter","abc123","my_db");// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)");
mysqli_close($con);?>
PHP & Database
Select Data From a Database Table
The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s)FROM table_name
<?php$con=mysqli_connect("example.com","peter","abc123","my_db");// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br>"; }
mysqli_close($con);?>
SELECT column_name(s)FROM table_name
WHERE column_name operator valueORDER BY column_name(s) ASC|DESC
PHP & Database
Update Data In a Database
The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value
<?php$con=mysqli_connect("example.com","peter","abc123","my_db");// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
mysqli_query($con,"UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'");
mysqli_close($con);?>
PHP & Database
Delete Data In a Database
The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_nameWHERE some_column = some_value
<?php$con=mysqli_connect("example.com","peter","abc123","my_db");// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysqli_close($con);?>
Thank You
BagheriNasab.ir