1. Single line
<?phpecho "Welcome to the world of php";?>Comments?in PHPThere are two types of comments used in php ?1. Single line comments :Single line comment used for short explanations. Declaration of Single line comment are two typesEither Begin with(#)Or backslash(//)<?php # This is the single line comment# This is the next line comment// This is also a single line comment.?>2. Multi-lines comments :Multi lines comments? used to comment multiple lines. Here we can give comments in bulk The bulk comments are enclose within (/*.....*/)<?php /* This is a comment with multiline view : Multiline Comments Demo */?>PHP VariablesVariable?is nothing it is just name of the memory location. A Variable is simply a container i.e used to store both numeric and non-numeric information.Variables in?PHP?starts with a?dollar($)?sign, followed by the name of the variable.The variable name must begin with a letter or the underscore character.A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )A variable name should not contain spaceAssigning Values to VariablesAssigning a value to a variable in PHP is quite east: use the equality(=) symbol, which also to the PHP's assignment operators.This assign value on the right side of the equation to the variable on the left.PHP Concatenation<?php ? $myCar = "Honda City";? echo $myCar." is riding";?><?php$first = 100;$second = 200;$third = $first + $second; ?echo "Sum = ".$third;?>Variable names in PHP are case-sensitive<?php$name="rexx";$NAME="rahul";echo $name."<br/>";echo $NAME;?>Super Global Variables in PHPPHP super global variable is used to access global variables from anywhere in the PHP script. PHP Super global variables is accessible inside the same page that defines it, as well as outside the page. while local variable's scope is within the page that defines it.The PHP super global variables are :1) $_GET["FormElementName"]It is used to collect value from a form(HTML script) sent with method='get'. information sent from a form with the method='get' is visible to everyone(it display on the browser URL bar).2) $_POST["FormElementName"]It is used to collect value in a form with method="post". Information sent from a form is invisible to others.(can check on address bar)3) $_REQUEST["FormElementName"]This can be used to collect data with both post and get method.4) $_FILES["FormElementName"]: It can be used to upload files from a client computer/system to a server.?OR$_FILES["FormElementName"]["ArrayIndex"]: Such as File Name, File Type, File Size, File temporary name.5) $_SESSION["VariableName"]A session variable is used to store information about a single user, and are available to all pages within one application.6) $_COOKIE["VariableName"]A cookie is used to identify a user. cookie is a small file that the server embedded on user computer.7) $_SERVER["ConstantName"]$_SERVER holds information about headers, paths, and script locations.Swapping Two Numbers<?php extract($_POST);if(isset($swap)){//first number$x=$fn;//second number$y=$sn;//third is blank$z=0;//now put x's values in $z$z=$x;//and Y's values into $x$x=$y;//again store $z in $y$y=$z;//Print the reversed Valuesecho "<p align='center'>Now First numebr is : ". $x ."<br/>";echo "and Second number is : ". $y."</p>";}?><form method="post"><table align="center"><tr><td>Enter First number</td><td><input type="text" name="fn"/></td></tr><tr><td>Enter Second number</td><td><input type="text" name="sn"/></td></tr><tr><td colspan="2" align="center"><input type="submit" value="Swap Numbers" name="swap"/></td></tr></table></form>Swap two variables value without using third variable in php<?php //swap two numbers without using third variable$x=20;$y=10;//add x and y, store in x i.e : 30$x=$x+$y;//subtract 10 from 30 i.e : 20 and store in y$y=$x-$y; //subtract 20 from 30 i.e : 10 and store in x$x=$x-$y;//now print the reversed valuesecho "Now x contains : ". $x ."<br/>";echo "and y contains : ". $y;?>Constant in PHPConstants are PHP container that remain constant and never changeConstants are used for data that is unchanged at multiple place within our program.Variables are temporary storage while Constants are permanent.Use Constants for values that remain fixed and referenced multiple times.<?php define('ConstName', 'value');?>PHP Magic ConstantThere are a number of predefined constants available to your scripts. We will use these constants as we need them; there's a sample:PHP Magic Constant__LINE__The current line number of the file.__FILE__The full path and filename of the file.__FUNCTION__The function name__CLASS__The class name__METHOD__The class method namePHP_VERSIONThe PHP versionPHP_INT_MAXThe PHP integer value limit<?phpecho "The Line number : ". __LINE__;?><?phpecho "Your file name :". __FILE__;?>PHP_VERSION<?phpecho "Current PHP Version you are using : ".PHP_VERSION;?>Difference between echo and print in PHPechoecho is a statement i.e used to display the output. it can be used with parentheses echo or without parentheses echo.echo can pass multiple string separated as ( , )echo doesn't return any valueecho is faster then printPrintPrint is also a statement i.e used to display the output. it can be used with parentheses print( ) or without parentheses print.using print can doesn't pass multiple argumentprint always return 1it is slower than echoPHP data typesData types specify the size and type of values that can be stored.Variable?does not need to be declared ITS DATA TYPE adding a value to it.PHP is a Loosely Typed Language so here no need to define data type.To check only data type use?gettype( )?function.To check value, data type and size use?var_dump( )?function.<?php$num=100;$fnum=100.0;$str="Hello";var_dump($num,$fnum,$str);?>Some Predefine functions to Check data type=>?is_int( ) :?Check given value is integer or not=>?is_float( ) :?Check given value is float or not=>?is_numeric( ) :?Check given value is either integer or float=>?is_string( ) :?Check given value is string or not=>?is_bool( ) :?Check given value is Boolean or not=>?is_array( ) :?Check given value is array or not=>?is_object( ) :?Check given value is object or not=>?is_null( ) :?Check given value is null or notCheck if given variable holds a integer type of value then print the sum otherwise show error message<?php $x = 1000; $y = 500; if(is_int($x) && is_int($y)) { $sum = $x + $y; echo "sum = ".$sum; } else { echo "both number must be integer"; } ?>PHP Form Example<html><head><title>form method</title></head><body><form method="post"><h2>Select Your car</h2><table border="1" align="center"><tr><td>Select Your car</td><td><Selct name="selType"><option value="porsche 911">Porsche 911</option><option value="Volkswagen Beetle">Volkswagen Beetle</option><option value="Ford Taurus">Ford Taurus</option></select></td></tr><tr><td>Color:</td><td><input type="text" name="txtColor"/></td></tr><tr><td><input type="submit"/></td></tr></table"></form></body></html><?php error_reporting(1); $type=$_POST['selType']; $color=$_POST['txtColor']; echo "<font color='blue'>Your $color $type is ready. safe driving! </font>";?>Form GET MethodGET method is unsecured method because it display all information on address bar/ url. By default method is get method. Using GET method limited data sends. GET method is faster way to send data.<html><head><title>get_browser</title><?phperror_reporting(1);$x=$_GET['f'];$y=$_GET['s'];$z=$x+$y;echo "Sum of two number = ".$z;?></head><body bgcolor="sky color"><form method="GET" ><table border="1" bgcolor="green"><tr><td>Enter your first number</td><td><input type="text" name="f"/></td></tr><tr><td>Enter your second number</td><td><input type="text" name="s"/></td></tr><tr align="center"><td colspan="2" ><input type="submit" value="+"/></td></tr></table></form></body></html>Form POST MethodPOST method is secured method because it hides all information. Using POST method unlimited data sends . POST method is slower method comparatively GET method.<html><head><title>get_browser</title><?phperror_reporting(1);$x = $_POST['f'];$y = $_POST['s'];$z = $x + $y;echo "Sum of two number = ".$z;?></head><body bgcolor="sky color"><form method="post" ><table border="1" bgcolor="green"><tr><td>Enter your first number</td><td><input type="text" name="f"/></td></tr><tr><td>Enter your second number</td><td><input type="text" name="s"/></td></tr><tr align="center"><td colspon="2" ><input type="submit" value="+"/></td></tr></table></form></body></html>How to use HTML Form actionAction is used to give reference/link of another page.Save it as DesingView.php<body><form method="post" action="Logic.php"> <table border="1" align="center"> <tr><td>Enter your name</td><td><input type="text" name="n"/></td></tr><tr><td colspan="2" align="center"><input type="submit" name="sub" value="SHOW MY NAME"/></td></tr></table></form></body>Save it as Logic.php<?php $name=$_POST['n'];echo "Welcome ".$name;?>PHP Display result in Textbox<?phpif(isset($_POST['add'])){$x=$_POST['fnum'];$y=$_POST['snum'];$sum=$x+$y; echo "Result:<input type='text' value='$sum'/>";}?><body><form method="post">Enter first number <input type="text" name="fnum"/><hr/>Enter second number <input type="text" name="snum"/><hr/> <input type="submit" name="add" value="ADD"/></form></body><?php$x=$_POST['fnum'];$y=$_POST['snum'];$sum=$x+$y;?> <body><form method="post">Result <input type="text" value="<?php echo @$sum;?>"/><hr/>Enter first number <input type="text" name="fnum"/><hr/>Enter second number <input type="text" name="snum"/><hr/> <input type="submit" value="ADD"/></form></body>Multiple submit buttons php different actions<?phpextract($_POST);//do addition and store the result in $resif(isset($add)){$res=$fnum+$snum;}//do subtraction and store the result in $resif(isset($sub)){$res=$fnum-$snum;}//do multiplicatio and store the result in $resif(isset($mult)){$res=$fnum*$snum;} ?> <html><head><title>Display the result in 3rd text box</title></head><body><form method="post"> <table align="center" border="1"> <Tr><th>Result</th><td><input type="text" value="<?php echo @$res;?>"/></td></tr><tr><th>Enter first number</th><td><input type="text" name="fnum"/></td></tr><tr><th>Enter second number</th><td><input type="text" name="snum"/></td></tr><tr><td align="center" colspan="2"><input type="submit" value="+" name="add"/><input type="submit" value="-" name="sub"/><input type="submit" value="*" name="mult"/></tr></table></form></body></html>Difference between ( == and === )<?php//another example$bool=(boolean)1;$int=(integer)1;//return true because both have same value.echo ($bool==$int);//return false because both have same value but diff data typeecho ($bool===$int);?>Write a program to check even number.(Number entered by user)<?php if(isset($_GET['save'])) {if($_GET['n']%2==0){echo $_GET['n']." is even number";} } ?><body><form method="get"> Enter Your number<input type="text" name="n"/><hr/> <input type="submit" value="check number" name="save"/> </form></body>Print related day name according to inputted number (1 - 7).<?php$day=$_POST['day'];if($day==1) { echo "Monday"; }else if($day==2){ echo "tuesday";} else if($day==3){ echo "wednesday";}else if($day==4){ echo "Thursday";}else if($day==5){ echo "friday";}else if($day==6){ echo "Saturday";}else if($day==7){ echo "Sunday";}else{echo "Wrong choice";}?><body><form method="post"> Enter Your number<input type="text" name="day"/><hr/> <input type="submit"/></form></body>Create PHP Calculator<?php extract($_POST);if(isset($save)){switch($ch){case '+':$res=$fn+$sn;break;case '-':$res=$fn-$sn;break;case '*':$res=$fn*$sn;break;}}?><!DOCTYP html><html><head><title>Calculator- switch</title></head><body><form method="post"><table border="1" align="center"><tr><th>Your Result</th><th><input type="number" readonly="readonly" disabled="disabled" value="<?php echo @$res;?>"/></th></tr> <tr><th>Enter your First num</th><th><input type="number" name="fn" value="<?php echo @$fn;?>"/></th></tr> <tr><th>Enter your Second num</th><th><input type="number" name="sn" value="<?php echo @$sn;?>"/></th></tr><tr><th>Select Your Choice</th><th><select name="ch"><option>+</option><option>-</option><option>*</option></select></th></tr><tr><th colspan="2"><input type="submit" name="save" value="Show Result"/></th></tr></table></form></body></html>Find the sum of 1 to 100.<?php$sum=0;for ($i=1; $i<=100; $i++){ $sum=$sum+$i; } echo $sum;?>Find all even numbers between 1 to 100<?phpfor ($i=2; $i<=100; $i+=2){ echo $i." ";} ?>Find all odd numbers between 1 to 100 using loop.<?phpfor ($i=1; $i<=99; $i+=2){ echo $i." "; } ?>Find the Sum of even and odd numbers between 1 to 100.<?phpfor ($i=1; $i<=100; $i++){ if($i%2==0) { $even=$even+$i; } else { $odd=$odd+$i; } } echo "Sum of even numbers=".$even."<br/>"; echo "Sum of odd numbers=".$odd; ?>Foreach Loop in PHPThe?foreach?Loop is used to display the value of array.You can define two parameter inside foreach separated through "as" keyword. First parameter must be existing array name which elements or key you want to display.At the Position of 2nd parameter, could define two variable: One for?key(index)?and another for?value.if you define only one variable at the position of 2nd parameter it contain arrays?value?(By default display array value).foreach ($array as $value) {code to be executed; } The following example demonstrates a loop that will print the values of the given array.<?php$person=array("alex", "simon","ravi");foreach ($person as $val) { echo $val."<br/>"; } ?>Define colors name and their index<?php$color=array("r"=>"red", "g"=>"green","b"=>"black","w"=>"white");foreach ($color as $key=>$val) { echo $key."--".$val."<br/>"; } ?>Find the Sum of given array<?php$array=array(10,11,12,13,14,15);$sum=0; foreach ($array as $x) { $sum=$sum+$x; } echo "Sum of given array = ".$sum;?>PHP numeric functionsSr. NoFunctionWhat it Does1ceil()Rounds a number up2floor()Rounds a number down3abs()Finds the absolute value of anumber4pow()Raises one number to the power of another5exp()Finds the exponent of a number6rand()Generates a random number7bindec()Converts a number from binary to decimal8decbin()Converts a number from decimal to binary9decoct()Converts a number from decimal to octal10octdec()Converts a number from octal to decimal11dechex()Converts a number from decimal to hexadecimal12hexdec()Converts a number from hexadecimal to decimal13number_format()Formats number with grouped thousands and decimals14printf()Formats a number using a custom specification15roundfind round number16sqrtfind square root of a number<?php $num=19.7 echo ceil($num); ?><?php $num=19.7 echo floor($num); ?><?php $num =-19.7 echo abs($num); ?><?php echo pow(4,3); ?><?php echo rand(10,99); ?><?php echo bindec(1000); ?><?php echo decbin(8); ?>Numeric ArraysNumeric arrays use number as access keys.An access key is a reference to a memory slot in an array variable.The access key is used whenever we want to read or assign a new value an array element.Below is the syntax for creating numeric array in php. Array Example<?php$variable_name[n] = value;?>Or<?php$variable_name = array(n => value, …);?>HERE,“$variable_name…” is the name of the variable“[n]” is the access index number of the element“value” is the value assigned to the array element.PHP Associative ArrayAssociative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.Below is the syntax for creating associative array in php.<?php$variable_name['key_name'] = value;$variable_name = array('keyname' => value);?>HERE,“$variable_name…” is the name of the variable“['key_name']” is the access index number of the element“value” is the value assigned to the array element.<?php$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");print_r($persons); echo ""; echo "Mary is a " . $persons["Mary"];?PHP Multi-dimensional arraysThese are arrays that contain other nested arrays.The advantage of multidimensional arrays is that they allow us to group related data together.Movie titleCategoryPink PantherComedyJohn EnglishComedyDie HardActionExpendablesActionThe Lord of the ringsEpicRomeo and JulietRomanceSee no evil hear no evilComedy<?php$movies =array("comedy" => array("Pink Panther", "John English", "See no evil hear no evil"),"action" => array("Die Hard", "Expendables"),"epic" => array("The Lord of the rings"),"Romance" => array("Romeo and Juliet"));print_r($movies);?><?php$film=array(??????????????? "comedy" => array(??????????????????????????????? 0 => "Pink Panther",??????????????????????????????? 1 => "john English",??????????????????????????????? 2 => "See no evil hear no evil"??????????????????????????????? ),??????????????? "action" => array (??????????????????????????????? 0 => "Die Hard",??????????????????????????????? 1 => "Expendables"??????????????????????????????? ),??????????????? "epic" => array (??????????????????????????????? 0 => "The Lord of the rings"??????????????????????????????? ),??????????????? "Romance" => array??????????????????????????????? (??????????????????????????????? 0 => "Romeo and Juliet"??????????????????????????????? ));echo $film["comedy"][0];?>PHP Array FunctionsCount function<?php$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");echo count($lecturers);?>The count function is used to count the number of elements that an php array contains. The code below shows the implementation.is_array functionThe is_array function is used to determine if a variable is an array or not. Let’s now look at an example that implements the is_array functions.<?php$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");echo is_array($lecturers);?>SortThis function is used to sort arrays by the values.If the values are alphanumeric, it sorts them in alphabetical order.If the values are numeric, it sorts them in ascending order.It removes the existing access keys and add new numeric keys.The output of this function is a numeric array<?php$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");sort($persons);print_r($persons);?>ksortThis function is used to sort the array using the key. The following example illustrates its usage.<?php$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");ksort($persons);print_r($persons);?>asortThis function is used to sort the array using the values. The following example illustrates its usage.<?php$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");asort($persons);print_r($persons);?>Why use arrays?Contents of Arrays can be stretched,Arrays easily help group related information such as server login details togetherArrays help write cleaner code.Arrays are special variables with the capacity to store multi values.Arrays are flexibility and can be easily stretched to accommodate more valuesNumeric arrays use numbers for the array keysPHP Associative array use descriptive names for array keysMultidimensional arrays contain other arrays inside them.<?php$paper[] = "Copier";$paper[] = "Inkjet";$paper[] = "Laser";$paper[] = "Photo";print_r($paper);?><?php$paper[0] = "Copier";$paper[1] = "Inkjet";$paper[2] = "Laser";$paper[3] = "Photo";print_r($paper);?><?php$paper[] = "Copier";$paper[] = "Inkjet";$paper[] = "Laser";$paper[] = "Photo";for ($j = 0 ; $j < 4 ; ++$j)echo "$j: $paper[$j]<br>";?><?php$paper['copier'] = "Copier & Multipurpose";$paper['inkjet'] = "Inkjet Printer";$paper['laser'] = "Laser Printer";$paper['photo'] = "Photographic Paper";echo $paper['laser'];?><?php$p1 = array("Copier", "Inkjet", "Laser", "Photo");echo "p1 element: " . $p1[2] . "<br>";$p2 = array('copier' => "Copier & Multipurpose",'inkjet' => "Inkjet Printer",'laser' => "Laser Printer",'photo' => "Photographic Paper");echo "p2 element: " . $p2['inkjet'] . "<br>";?><?php$paper = array("Copier", "Inkjet", "Laser", "Photo");$j = 0;foreach($paper as $item){echo "$j: $item<br>";++$j;}?><?php$paper = array('copier' => "Copier & Multipurpose",'inkjet' => "Inkjet Printer",'laser' => "Laser Printer",'photo' => "Photographic Paper");foreach($paper as $item => $description)echo "$item: $description<br>";?><?php$paper = array('copier' => "Copier & Multipurpose",'inkjet' => "Inkjet Printer",'laser' => "Laser Printer",'photo' => "Photographic Paper");while (list($item, $description) = each($paper))echo "$item: $description<br>";?><?phplist($a, $b) = array('Alice', 'Bob');echo "a=$a b=$b";?><?php$products = array('paper' => array('copier' => "Copier & Multipurpose",'inkjet' => "Inkjet Printer",'laser' => "Laser Printer",'photo' => "Photographic Paper"),'pens' => array('ball' => "Ball Point",'hilite' => "Highlighters",'marker' => "Markers"),'misc' => array('tape' => "Sticky Tape",'glue' => "Adhesives", 'clips' => "Paperclips"));echo "<pre>";foreach($products as $section => $items)foreach($items as $key => $value)echo "$section:\t$key\t($value)<br>";echo "</pre>";?>Array Functionsecho (is_array($fred)) ? "Is an array" : "Is not an array";echo count($fred);shuffle($cards);<?php$temp = explode(' ', "This is a sentence with seven words");print_r($temp);?><?php$temp = explode('***', "A***sentence***with***asterisks");print_r($temp);?><?php$fname = "Doctor";$sname = "Who";$planet = "Gallifrey";$system = "Gridlock";$constellation = "Kasterborous";$contact = compact('fname', 'sname', 'planet', 'system', 'constellation');print_r($contact);?>reset($fred); // Throw away return value$item = reset($fred); // Keep first element of the array in $itemend($fred);$item = end($fred);Database ConnectivityINDEX.PHP<html><body><h1>A small example page to insert some data in to the MySQL database using PHP</h1><form action="insert.php" method="post">Firstname: <input type="text" name="fname" /><br><br>Lastname: <input type="text" name="lname" /><br><br>?<input type="submit" /></form></body></html>INSERT.PHP<html><body> <?php$con = mysql_connect("127.0.0.1","root","");if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("example", $con); $sql="INSERT INTO user (fname, lname)VALUES('$_POST[fname]','$_POST[lname]')";$sql = "INSERT INTO user (fname, lname)VALUES ('John', 'Doe');"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }echo "1 record added"; mysql_close($con)?></body></html>Select:<html><body> <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = ''; $dbname = 'example'; $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } echo 'Connected successfully <br>';$sol = "SELECT * FROM user";$result = mysqli_query($conn, $sol);if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "First Name: " . $row["fname"]. "<br>"; echo "Last Name: " . $row["lname"]. "<br>"; } } else { echo "0 results"; } mysql_close($conn);?></body></html>DELETE FROM user WHERE fname = "Devi"UPDATE tutorials_inf SET name="althamas" WHERE name="ram" ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- 1 line words of encouragement
- ansi single line diagram symbols
- line by line song lyric generator
- 1040 schedule 1 line 1
- 1040 schedule 1 line 16
- schedule 1 line 22 1040
- 1040 schedule 1 line 8
- irs schedule 1 line 22
- single mothers vs single fathers statistics
- printable number line 1 10
- 941 worksheet 1 line 2a i
- 941 part 1 line 2