Download presentation
Presentation is loading. Please wait.
Published byAdele Flynn Modified over 9 years ago
1
PHP / MySQL
2
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
3
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"
4
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
5
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.netwww.php.net PHP is easy to learn and runs efficiently on the server side
6
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
7
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
8
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
9
Basic PHP Syntax A PHP script can be placed anywhere in the document. A PHP script starts with : The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting code.
10
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.
11
Much Like Algebra x=5 y=6 z=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.
12
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 variable A variable name must start with a letter or the underscore character A variable name cannot start with a number A 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:
13
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.
14
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);
15
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
16
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']; ?>
17
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"); ?>
18
Samples <?php echo strlen("Hello world!"); echo strpos("Hello world!","world"); echo chr(97); echo ord("a"); echo md5("hello"); echo trim(" test "); echo strip_tags("mbn ttt"); ?>
19
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.
20
PHP Arithmetic Operators OperatorNameExampleResult + Addition$x + $ySum of $x and $y - Subtraction$x - $yDifference of $x and $y * Multiplication$x * $yProduct of $x and $y / Division$x / $yQuotient of $x and $y % Modulus$x % $yRemainder of $x divided by $y Example
21
PHP Assignment Operators AssignmentSame as...Description x = y The left operand gets set to the value of the expression on the right x += y x = x + yAddition x -= y x = x - ySubtraction x *= y x = x * yMultiplication x /= y x = x / yDivision x %= y x = x % yModulus Example
22
PHP String Operators Example OperatorNameExampleResult. Concatenation $txt1 = "Hello" $txt2 = $txt1." world!" Now $txt2 contains "Hello world!".= Concatenation assignment$txt1 = "Hello" $txt1.= " world!" Now $txt1 contains "Hello world!"
23
PHP Increment / Decrement Operators Example OperatorNameDescription ++$x Pre-incrementIncrements $x by one, then returns $x $x++ Post-incrementReturns $x, then increments $x by one --$x Pre-decrementDecrements $x by one, then returns $x $x-- Post-decrementReturns $x, then decrements $x by one
24
PHP Comparison Operators "; var_dump($x === $y); echo " "; var_dump($x != $y); echo " "; var_dump($x !== $y); echo " "; ?> OperatorNameExampleResult == Equal$x == $yTrue 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 != $yTrue if $x is not equal to $y <> Not equal$x <> $yTrue 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 > $yTrue if $x is greater than $y < Less than$x < $yTrue if $x is less than $y >= Greater than or equal to$x >= $yTrue if $x is greater than or equal to $y <= Less than or equal to$x <= $yTrue if $x is less than or equal to $y
25
PHP Conditional Statements if (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; }
26
PHP Conditional Statements switch (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; }
27
PHP Loops while (condition is true) { code to be executed; } "; $x++; } ?>
28
PHP Loops do { code to be executed; } while (condition is true); "; $x++; } while ($x
29
PHP Loops for (init counter ; test counter ; increment counter) { code to be executed; } "; } ?>
30
PHP Loops foreach ($array as $value) { code to be executed; } "; } ?>
31
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; } ?>
32
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 "; } familyName(“ali","1975"); familyName(“hasan","1978"); familyName(“reza","1983"); ?>
33
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 "; } setHeight(350); setHeight(); // will use the default value of 50 setHeight(135); setHeight(80); ?>
34
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). " "; echo "7 + 13 = ". sum(7,13). " "; echo "2 + 4 = ". sum(2,4); ?>
35
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.
36
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 " Test variables inside the function: "; echo "Variable x is: $x"; echo " "; echo "Variable y is: $y"; } myTest(); echo " Test variables outside the function: "; echo "Variable x is: $x"; echo " "; echo "Variable y is: $y"; ?>
37
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 ?>
38
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 ?>
39
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 ?>
40
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(); ?>
41
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]. "."; ?>
42
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 "; } ?>
43
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."; ?>
44
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 " "; }?>
45
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 "; } ?>
46
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. Welcome to my home page! Some text.
47
File Upload Filename:
48
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); "; else echo "Welcome guest! "; ?> How to Retrieve a Cookie Value? How to Delete a Cookie?
49
Sessions A 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 tag You can also completely destroy the session by calling the session_destroy() function: Destroying a Session
50
mail() Function ParameterDescription toRequired. Specifies the recipient's email address(es) subjectRequired. Specifies the email's subject line. Note: This parameter cannot contain any newline characters messageRequired. 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 headersOptional. Specifies additional headers such as "From", "Cc", "Bcc", etc. The additional headers should be separated with a CRLF (\r\n) parametersOptional. Specifies any additional parameters Syntax mail(to,subject,message,headers,parameters)
51
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);
52
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,...)
53
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 "; } mysqli_close($con); ?> SELECT column_name(s) FROM table_name WHERE column_name operator value ORDER BY column_name(s) ASC|DESC
54
PHP & Database Update Data In a Database The UPDATE statement is used to update existing records in a table. Syntax UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
55
PHP & Database Delete Data In a Database The DELETE FROM statement is used to delete records from a database table. Syntax DELETE FROM table_name WHERE some_column = some_value
56
Thank You BagheriNasab.ir
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.