Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP/MySQL.

Similar presentations


Presentation on theme: "PHP/MySQL."— Presentation transcript:

1 PHP/MySQL

2 What is PHP? PHP == ‘Hypertext Preprocessor’
Open-source, server-side scripting language ,Used to generate dynamic web-pages PHP scripts reside between reserved PHP tags This allows the programmer to embed PHP scripts within HTML pages Interpreted language, scripts are parsed at run-time rather than compiled beforehand Executed on the server-side Source-code not visible by client ‘View Source’ in browsers does not display the PHP code Various built-in functions allow for fast development Compatible with many popular databases

3 What does PHP code look like?
Structurally similar to C/C++ Supports procedural and object-oriented paradigm (to some degree) All PHP statements end with a semi-colon Each PHP script must be enclosed in the reserved PHP tag <?php … ?>

4 Comments in PHP // C++ and Java-style comment # Shell-style comments
/* C-style comments These can span multiple lines */

5 PHP variables must begin with a “$” sign
Variables in PHP PHP variables must begin with a “$” sign Case-sensitive ($Foo != $foo != $fOo) Global and locally-scoped variables Global variables can be used anywhere Local variables restricted to a function or class Certain variable names reserved by PHP Form variables ($_POST, $_GET) Server variables ($_SERVER) Etc.

6 Variable usage <?php
$foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?>

7 Echo The PHP command ‘echo’ is used to output the parameters passed to it The typical usage for this is to send data to the client’s web-browser Syntax echo (string arg1 [, string argn...]) In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function

8 Echo example <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable echo $bar; // Outputs Hello echo $foo,$bar; // Outputs 25Hello echo “5x5=”,$foo; // Outputs 5x5=25 echo “5x5=$foo”; // Outputs 5x5=25 echo ‘5x5=$foo’; // Outputs 5x5=$foo ?> Note:how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25 Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP This is true for both variables and character escape-sequences (such as “\n” or “\\”)

9 Operations Arithmetic (+, -, *, /, %) and String (.)
Assignment (=) and combined assignment $a = 3; $a += 5; // sets $a to 8; $b = "Hello "; $b .= "There!"; // sets $b to "Hello There!"; Bitwise (&, |, ^, ~, <<, >>) $a ^ $b (Xor: Bits that are set in $a or $b but not both are set.) ~ $a (Not: Bits that are set in $a are not set, and vice versa.) Comparison (==, ===, !=, !==, <, >, <=, >=) Conditional operators (condition)?exp1:exp2;

10 Use a period to join strings into one.
Concatenation Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP

11 Escaping the Character
If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks to ignore and display them. <?php $heading=“\”Computer Science\””; Print $heading; ?> “Computer Science”

12 An array can store one or more values in a single variable name.
Arrays An array can store one or more values in a single variable name. There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays

13 Array examples Numeric array:-
$names = array("Peter","Quagmire","Joe"); Associative array:- $ages = array("Peter"=>32, "Glenn"=>30, "Joe"=>34); Multidimensional Array:- $families = array ( "Fruits"=>array ( "Apple", "Mango", "Orange" ), "Vegetable"=>array ( "carrot" ), "Flower"=>array ( "Rose", "Lotus", "Lilly" ) );

14 PHP Control Structures
Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script. Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops). Example if/else : if ($foo == 0) { echo ‘The variable foo is equal to 0’; } else if (($foo > 0) && ($foo <= 5)) { echo ‘The variable foo is between 1 and 5’; else { echo ‘The variable foo is equal to ‘.$foo;

15 If (condition) { Statements; } Else Statement; You are not John.
If ... Else... If (condition) { Statements; } Else Statement; <?php $user=”jeo”; If($user==“John”) { Print “Hello John.”; } Else Print “You are not John.”; ?> You are not John.

16 While (condition) { Statements; } While Loops
<?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; } ?> While (condition) { Statements; } hello PHP. hello PHP. hello PHP.

17 do { Statements; }While (condition); Do While Loops
<?php $count=0; do { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; }While($count<2); ?> do { Statements; }While (condition); hello PHP. hello PHP. hello PHP.

18 for (initialization;condition;inc/dec) { Statements; }
For loop for (initialization;condition;inc/dec) { Statements; } <?php $count=0; for($count=0;$count<2;$count++) { Print “hello PHP. ”; } ?> hello PHP. hello PHP. hello PHP.

19 Switch case The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. <?php $i='apple'; switch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; case "cake": echo "i is cake"; } ?>

20 Go to The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. <?php echo “hai”; goto a; echo 'hello'; a: echo 'welcome'; ?> Other key words are return; continue;

21 Date Display $datedisplay=date(“yyyy/m/d”); Print $datedisplay;
# If the date is April 1st, 2009 # It would display as 2009/4/1 2009/4/1 $datedisplay=date(“l, F m, Y”); Print $datedisplay; # If the date is April 1st, 2009 # Wednesday, April 1, 2009 Wednesday, April 1, 2009

22 Month, Day & Date Format Symbols
Jan F January m 01 n 1 Day of Month d 01 J 1 Day of Week l Monday D Mon

23 String functions Some string functions
strlen - Used to find a length of the string. strlen(string); substr - Return part of a string substr(string,start,length) ; str_replace - The str_replace() function replaces some characters with some other characters in a string. str_replace(find,replace,string,count) ; strrev - Reverse a string. strrev ( string ); strcmp - compares two strings. strcmp(string1,string2) ; trim – used to remove the whitespace . trim(string);

24 Functions MUST be defined before then can be called
Function headers are of the format Note that no return type is specified Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…)) function functionName($arg_1, $arg_2, …, $arg_n)

25 Functions example <?php // This is a function
function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2;   return $arg_2; } $result_1 = foo(12, 3); // Store the function echo $result_1; // Outputs 36 echo foo(12, 3); // Outputs 36 ?>

26 Classes and Objects a class represents an object, with associated methods and variables class definitions begin with the keyword class. Reusable piece of code. Has its own ‘local scope’. <?php class simpleClass { public $furite=”apple”; function display() { echo $this → furite; } $objSampleClass= new simpleClass; $objSampleClass → display(); ?>

27 Classes and Objects If you need to use the class variables within any class actions, use the special variable $this in the definition: class sampleClass { public $name; public function display() echo $this->name; }

28 Constructor A constructor method is a function that is automatically executed when the class is first instantiated. Create a constructor by including a function within the class definition with the __construct name. Remember.. if the constructor requires arguments, they must be passed when it is instantiated.

29 Constructor Example <?php class sampleClass { public $name;
public function __construct($nametext) { $this->name = $nametext; } public function display() { echo $this->name; } ?> Constructor function 29

30 Inheritance The child classes ‘inherit’ all the methods and variables of the parent class, and can add extra ones of their own. e.g. the child classes testClass inherits the variable ‘name’ and method ‘diaplay’ from the sampleClass class, and can add extra ones…

31 Inheritance Examples class testClass extends sampleClass {
public $age; public function setType($age) { if ($height<3) { $this->type = ‘infant’; } elseif ($height>7) { $this->type = ‘child’; else { $this->type = ‘adult’;

32 Inheritance Example The use of the extends keyword to indicate that the testClass is a child of the sampleClass class. $classObj = new testClass(“hai”); $classObj->setType(12); echo $classObj->name; echo $classObj->type; echo $classObj->display();

33 Child class constructor
If the child class possesses a constructor function, it is executed and any parent constructor is ignored. If the child class does not have a constructor, the parent’s constructor is executed. If the child and parent does not have a constructor, the grandparent constructor is attempted…

34 Include files In four ways we can include the external files , they are include(file.php); include_once(file.php); require(file.php); require_once(file.php); Include:- The include statement includes and evaluates the specified file. produces a Warning if the file cannot be loaded. (Execution continues) include_once:-This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again.

35 Include files require :-will throw a PHP Fatal Error if the file cannot be loaded. (Execution stops) require_once:- This is same as require .The difference is, if the particular file is already required then it wont require the same file once again.

36 Include Files Include “opendb.php”; Include “closedb.php”;
This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: <hr SIZE=11 NOSHADE WIDTH=“100%”> <i>Copyright © KSU </i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL:

37 PHP form Access to the HTTP POST and GET data is simple in PHP
The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form>

38 PHP 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. PHP session start- By using session_start() we can start the sessions Every page that uses session data must be proceeded by the session_start() function

39 Session variables When you want to store user data in a session use the $_SESSION associative array. This is where you both store and retrieve session data. Syntax:- $_SESSION['variableName']=assignedValue;

40 Cleaning and Destroying Session
Although a session's data is temporary and we can explicitly clean some data whenever we want by using unset keyword. We can also completely destroy the session entirely by calling the session_destroy function.

41 MySQL is the most popular database system used with PHP. Query:-
select * from user_details; The table have two word, it should be separate with _ symbol Limit :- limit is used to get a paritcular number of row from a table.

42 MySQL User can create a database by using the below query.
create dtatabase databaseName; Connecting database mysql_connect(host,username,password); Example:- $conn=mysql_connect("localhost","root","infiniti") or die(mysql_error()); Selecting database mysql_select_db("databaseName",databaseConnection) mysql_select_db("phoneBook",$conn) or die(mysql_error());

43 MySQL mysql_query – is used to execute the query.
mysql_num_rows – is used to get a no of row after the query execution. mysql_fetch_assoc - Fetch a result row as an associative array. mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both mysql_fetch_row - Get a result row as an enumerated array mysql_insert_id - Get the ID generated in the last query ORDER BY – We can order the result row by using order by comment. desc - descending order

44 Example <?php $conn=mysql_connect("localhost","root","infiniti") or die(mysql_error()); mysql_select_db("phoneBook",$conn) or die(mysql_error()); $sql="select * from user_details order by user_id desc limit 10"; $res=mysql_query($sql,$conn); $row=mysql_fetch_array($res); print_r($row); ?>

45 Primary key and foreign key
Example for primary key:- create table user_details(user_id int NOT NULL auto_increment,login_ varchar(100),password varchar(30),PRIMARY KEY(user_id)); Example for foreign key:- create table employee_details(employee_id int NOT NULL auto_increment,user_id int,first_name varchar(50),last_name varchar(50),age int,PRIMARY KEY(employee_id),FOREIGN KEY references user_details(user_id);

46 Example Query Creating table Syntax:-
create table tableName(field1 datatype,field2 datatype,.....); Example:- create table user_details (user_id int,user_name varchar(50)); Altering table alter table tableName add column field1 datatype,field2 datatype,..... alter table tableName change column oldField newField datatype,..... alter table user_details add column password varchar(30) alter table user_details change column password user_password varchar(30);

47 Example Query Table Deletion Syntax:-
delete table tableName where condition1 and condition2,.. Example:- delete from user_details where user_name='jeo'; Truncating table truncate table tableName truncate table user_details; Drop table drop table tableName drop table user_details;

48 Example Query Inserting values Syntax:-
insert into table tableName values(field1,field2,.....); Example:- insert into table user_details values(1,'jeo'); Selecting values select * from tableName where condition1 and condition2,..; select * from user_details where user_name='jeo'; updateing values update tableName set column1=value1,column2=value2,... where condition1 and condition2,..; update user_details set user_name=”bala” where user_name=”jeo”;

49 Ajax – Asynchronous Javascript And Xml
By using ajax we can internally request the server and get the response without page reloading

50 Ajax syntax function testFunction() { if(window.XMLHttpRequest) {
Var xmlHttp=new XMLHttpRequest(); } else { Var xmlHttp= new ActiveXObject("Microsoft .XMLHTTP"); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState ==4 && xmlHttp.status ==200) { //coding for the process xmlHttp.open(“GET”,”url”,true); xmlHttp.send();

51 GET method is more faster then POST method in ajax.
In this sytax true - asynchronous false - synchronous GET method is more faster then POST method in ajax. While passing more values we should use POST method. Here readystate 4 means success.

52 Ajax Example HTML codings:- <html> <body>
<p><b>Start typing a user name in the input field below:</b></p> <form> User name: <input type="text" id=”userName” name=”userName”> <input type=”button” onclick=”testFunction()”> </form> <div id=”result”></div> </body> </html>

53 Ajax Example Ajax Example Ajax Example Script Coding:-
function testFunction(){ Var xmlHttp; var userName=document.getElementById("userName").value; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlHttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlHttp.readyState==4 && xmlHttp.status==200) { document.getElementById("result").innerHTML=xmlHttp.responseText; xmlHttp.open("GET","display.php?userName="+userName,true); xmlHttp.send(); Ajax Example Ajax Example

54 Ajax Example Ajax Example Ajax Example Script Coding:-
function testFunction(){ Var xmlHttp; var userName=document.getElementById("userName").value; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlHttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlHttp.readyState==4 && xmlHttp.status==200) { document.getElementById("result").innerHTML=xmlHttp.responseText; xmlHttp.open("GET","display.php?userName="+userName,true); xmlHttp.send(); Ajax Example Ajax Example

55 PHP coding:- <?php ?> $ipAddress=$_SERVER['REMOTE_ADDR'];
Ajax Example PHP coding:- <?php $ipAddress=$_SERVER['REMOTE_ADDR']; $userName=$_REQUEST['userName”]; echo “Welcome “.$userName.” . Your IP address is ” .$ipAddress; ?>

56 Xajax Xajax is a framework. xajax is an open source PHP class library implementation of Ajax that gives developers the ability to create web-based Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page.

57 Xajax xajax is designed to be extremely easy to implement in both existing web applications as well as new projects. You can add the power of xajax to nearly any PHP script in seven easy steps: 1. Include the xajax class library: require_once("xajax_core/xajax.inc.php"); 2. Instantiate the xajax object: $xajax = new xajax(); 3. Register the names of the PHP functions you want to be able to call through xajax: $xajax->registerFunction("myFunction");

58 Xajax 4. Write the PHP functions you have registered and use the xajaxResponse object to return XML commands from them: function myFunction($arg) { $newContent = "Value of \$arg: ".$arg; // Instantiate the xajaxResponse object $objResponse = new xajaxResponse(); // add a command to the response to assign the innerHTML attribute of // the element with id="SomeElementId" to whatever the new content is $objResponse->assign("SomeElementId","innerHTML", $newContent); //return the xajaxResponse object return $objResponse; }

59 Xajax 5. Before your script sends any output, have xajax handle any requests: $xajax->processRequest(); 6. Between your tags, tell xajax to generate the necessary JavaScript: <?php $xajax->printJavascript(); ?> 7. Call the function from a JavaScript event or function in your application: <div id="SomeElementId"></div> <button onclick="xajax_myFunction('It worked!');">

60 Xajax The xajax hava a many commands they are below

61 Command for getting the form values
Xajax Command for getting the form values xajax.getFormValues('formName');


Download ppt "PHP/MySQL."

Similar presentations


Ads by Google