6 PHP Components PHP is one of the most popular development languages for building dynamic web applications today. PHP offers many advantages; it is fast, stable, secure, easy to use and open source. Being familiar with PHP and having a good toolbox for working effectively with PHP is essential for most Web Developers because you will run into some PHP code anyone will run into PHP now and then! In this chapter we will discuss some of useful PHP Components that you can use to test, develop Graphics, debug and deploy your PHP applications 6.1 GD Library The GD library is used for dynamic image creation. From PHP we use with the GD library to create GIF, PNG or JPG images instantly from our code. This allows us to do things such as create charts on the fly, created an anti-robot security image, create thumbnail images, or even build images from other so, the GD library allows you to alter, manipulate, and create images quite simply. Today, we’ll learn the basics of using PHP and the GD library You will need to make sure the GD library is installed and activated on your server. Don’t know how to do this? No worries, just create a PHP file on your server and type in. <?php echo phpinfo(); ?> Now access the page in your browser and you’ll see a giant list detailing the features of your version of PHP. Scroll down a bit and look for the ‘GD’ heading to make sure it is enabled. If it is not, you will need to contact your hosting company. Luckily, most servers I have worked on already have the GD library installed and activated. 6.1.1 imagecreate() Create a new palette based image or you can say it creates and set a blank canvas, imagecreate() returns an image identifier representing a blank image of specified size. Syntax resource imagecreate ( int $width , int $height ) $width set’s image width $height set’s image height Returns an image resource identifier on success, False on error Example <?php $canvas=imagecreate(200,200) ?> Above example will not display anything it will just create a canvas of 200 width and 200 height of that canvas, how to fill that canvas and draw any image like circle, rectangle will be possible using different functions lets see them one by one. 6.1.2 imagecolorallocate() Allocate a color for an image, imagecolorallocate() must be called to create each color that is to be used in the image represented by image. Imagecolorallocate() Returns a color identifier representing the color composed of the given RGB components. Syntax int imagecolorallocate ( resource $image , int $red , int $green , int $blue ) image An image resource, returned by one of the image creation functions, such as imagecreate() red value of red component green value of green component blue value of blue component These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF. Example <?php image = imagecreate(125, 125); &height //create basic image canvas of 125 width $blue = imagecolorallocate($image, 0, 0, 255); imagepng($image); ?> //Set the background color //save the image as a png and output Output Figure 6.1 example of imagecolorallocate() 6.1.3 imageline() Draws a line between the two given points. Syntax bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) image An image resource, returned by one of the image creation functions such as imagecreate() x1 x coordinate for first point. y1 y-coordinate for first point. x2 x-coordinate for second point. y2 y-coordinate for second point color A color identifier created with imagecolorallocate() Returns TRUE on success or FALSE on failure. Example <?php // Create a 200 x 200 image $canvas = imagecreate(200, 200); // Allocate colors $black=imagecolorallocate($canvas,255,255,0); $pink = imagecolorallocate($canvas, 255, 105, 180); $white = imagecolorallocate($canvas, 255, 255, 255); $red = imagecolorallocate($canvas, 255, 0, 0); imageline ($canvas,5, 5, 195, 5, $red); imageline ($canvas,5, 5, 195, 195, $pink); imagejpeg($canvas); imagedestroy($canvas); ?> Output Figure 6.2 example of imageline() 6.1.4 Imagerectangle() imagerectangle() creates a rectangle starting at the specified coordinates. Returns TRUE on success or FALSE on failure. Syntax bool imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) image An image resource, returned by one of the image creation functions such as imagecreate() x1 Upper left x coordinate y1 Upper left y coordinate x2 Bottom right x coordinate y2 Bottom right y coordinate color A color identifier created with imagecolorallocate() Example <?php // Create a 200 x 200 image $canvas = imagecreate(200, 200); // Allocate colors $black=imagecolorallocate($canvas,0,0,0); $pink = imagecolorallocate($canvas, 255, 105, 180); $white = imagecolorallocate($canvas, 255, 255, 255); $red = imagecolorallocate($canvas, 255, 0, 0); // Draw three rectangles each with its own color imagerectangle($canvas, 50, 50, 150, 150, $pink); imagerectangle($canvas, 60, 60,140,140 , $white); imagerectangle($canvas, 70, 70,130,130 , $red); imagejpeg($canvas); ?> Output Figure 6.3 Example of imagerectangle() 6.1.5 Imagefilledrectangle() Creates a rectangle filled with color in the given image starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image. Syntax bool imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) image An image resource, returned by one of the image creation functions such as imagecreate() x1 x-coordinate for point 1. y1 y-coordinate for point 1. x2 x-coordinate for point 2. y2 y-coordinate for point 2 color A color identifier created with imagecolorallocate() Example <?php $canvas = imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($canvas, 255, 255, 0); // yellow $red = imagecolorallocate($canvas, 255, 0, 0); $blue = imagecolorallocate($canvas, 0, 0, 255); // red // blue imagerectangle ($canvas, 5, 10, 195, 50, $red); imagefilledrectangle ($canvas, 5, 100, 195, 140, $blue); imagepng($canvas); ?> Output Figure 6.4 example of imagefilledrectangle() 6.1.6 imageellipse() Draws an ellipse centered at the specified coordinates Syntax bool imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color ) image An image resource, returned by one of the image creation functions such as imagecreate() cx x coordinat of the center cy y-coordinate of the center. Width The ellipse width Height The ellipse height color A color identifier created with imagecolorallocate() Returns TRUE on success or FALSE on failure. Example <?php // Create a blank image. $image = imagecreate(400, 300); $background_color = imagecolorallocate($image, 255, 255,255); // white $col_ellipse = imagecolorallocate($image, 255, 0, 0);//Choose a color for the ellipse imageellipse($image, 200, 150, 300, 200, $col_ellipse);// Draw the ellipse. imagepng($image); ?> Output Figure 6.5 example of imageellipse() 6.1.7 imagefilledellipse() Draws an ellipse centered at the specified coordinate on the given image. Its Returns TRUE on success or FALSE on failure. Syntax bool imagefilledellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color ) image cx cy Width An image resource, returned by one of the image creation functions such as imagecreate() x coordinat of the center y-coordinate of the center. The ellipse width Height color The ellipse height A color identifier created with imagecolorallocate() Example <?php $canvas = imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($canvas, 255, 255, 0); // yellow $red = imagecolorallocate($canvas, 255, 0, 0); // red $blue = imagecolorallocate($canvas, 0, 0, 255); // blue imageellipse($canvas, 50, 50, 40, 60, $red); imagefilledellipse($canvas, 150, 150, 60, 40, $blue); imagepng($canvas); ?> Output Figure 6.6 example of imagefilledellipse() 6.1.8 imagearc() imagearc() draws an arc of circle centered at the given coordinates, its return true on success, false on failure bool imagearc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color ) image cx cy width height start end color Example <?php An image resource, returned by one of the image creation functions such as imagecreate() x coordinat of the center y-coordinate of the center. The ellipse width The ellipse height the arc start angle, in degree The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise. A color identifier created with imagecolorallocate() $im = imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255,0,0); $blue = imagecolorallocate($im, 0, 0, 255); $green = imagecolorallocate($im, 0, 255, 0); $sky = imagecolorallocate($im, 100, 255,255); imagearc($im, 20, 50, 40, 80, 0, 90, $red); imagearc($im, 70, 50, 40, 80, 0, 180, $green); imagearc($im, 120, 50, 40, 80, 0, 270, $blue); imagearc($im, 170, 50, 40, 80, 0, 360, $sky); imagepng($im); // red // blue ?> Ouput Figure 6.7 example of imagearc() X and Y define thy position of the center of the arc within the image, Width and height are the dimensions of the complete circle formed by the arc. arc start and arc end are the start and the end of the arc in degrees. If start is zero, as in the example, the figure will start in the right. 6.1.9 imagefilledarc() Draws a partial arc centered at the specified coordinate in the given image. Syntax bool imagefilledarc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color , int $style ) image cx cy width height start end color Style An image resource, returned by one of the image creation functions such as imagecreate() x coordinat of the center y-coordinate of the center. The ellipse width The ellipse height the arc start angle, in degree The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise. A color identifier created with imagecolorallocate() Style we can specify four value IMG_ARC_PIE IMG_ARC_CHORD IMG_ARC_NOFILL IMG_ARC_EDGED IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'. Example <?php // create a 200*200 image $img = imagecreate(200, 200); $white = imagecolorallocate($img, 255,255, 255); // allocate some colors $black = imagecolorallocate($img, 0, 0, 0); $red = imagecolorallocate($img, 255, 0, 0); $green = imagecolorallocate($img, 0, 255, 0); $blue = imagecolorallocate($img, 0, 0, 255); $yellow = imagecolorallocate($img, 255, 255, 0); // draw the head imagearc($img, 100, 100, 200, 200, 0, 360, $black); imagefilledarc($img,100,100,200,200,0,360,$yellow,IMG_ARC_PIE ); // mouth imagearc($img, 100, 100, 150, 150, 25, 155, $red); // left and then the right eye imagearc($img, 60, 75, 50, 50, 0, 360, $green); imagearc($img, 140, 75, 50, 50, 0, 360, $blue); imagefilledarc($img,70,75,25,25,0,360,$black,IMG_ARC_PIE ); imagefilledarc($img,130,75,25,25,0,360,$black,IMG_ARC_PIE ); imagepng($img); ?> Ouptut Figure 6.8 example of imagefilledarc() 6.1.10 imagepolygon() imagepolygon() creates a polygon in the given image. Syntax bool imagepolygon ( resource $image , array $points , int $num_points , int $color ) image points num_points color An image resource, returned by one of the image creation functions such as imagecreate() An array containing the polygon's vertices points[0]= x0 points[1]= y0 points[2]= x1 points[3]= y1 Total number of points A color identifier created with imagecolorallocate() 6.1.11 imagefilledpolygon() imagefilledpolygon() creates a filled polygon in the given image Syntax bool imagefilledpolygon ( resource $image , array $points , int $num_points , int $color ) image An image resource, returned by one of the image creation functions such as imagecreate() points num_points color An array containing the polygon's vertices points[0]= x0 points[1]= y0 points[2]= x1 points[3]= y1 Total number of points A color identifier created with imagecolorallocate() Example of imagepolygon() and imagefilledpolygon() <?php // Create a blank image $image = imagecreatetruecolor(400, 300); // Allocate a color for the polygon $blue = imagecolorallocate($image, 0, 0, 255); // Draw the polygon imagepolygon($image, array( 0, 0, 100, 200, 300, 200 ),3,$col_poly); imagefilledpolygon($image, array( 0, 0, 100, 200, 300, 200 ),3,$blue); //fill the polygon with specified color imagepng($image); ?> Figure 6.9 example of imagepolygon() & imagefilledpolygon() 6.1.12 imagestring() Draw a string at a given coordinates Syntax bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color ) image font x y String color An image resource, returned by one of the image creation functions such as imagecreate() Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding x-coordinate of the upper left corner y-coordinate of the upper left corner. The string to be written. A color identifier created with imagecolorallocate() Example <?php // Create a 100*30 image $im = imagecreate(350, 30); // purple background and blue text $bg = imagecolorallocate($im, 150, 0,255); $textcolor = imagecolorallocate($im, 0, 0, 255); // Write the string at the top left imagestring($im, 5, 0, 0, 'Welcome to PHP GD Library Function!', $textcolor); // Output the image header('Content-type: image/png'); imagepng($im); imagedestroy($im); ?> Output Figure 6.10 example of imagestring() 6.1.13 imagerotate() Rotates the image image using the given angle in degrees, The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image. Syntax resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] ) image An image resource, returned by one of the image creation functions such as imagecreate() angle Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise. Values may be positive (90, 180...) or negative (-90,-180...). bgd_color Specifies the color of the uncovered zone after the rotation, $color indicates the color to be used as background when necessary (when rotation angle is different to 90, 180 and 270). For example when rotation is 45 degrees, the size of the figure will be altered, as shown bellow. As a consequence a background color is required to fill the new surface. Returns an image resource for the rotated image, or FALSE on failure Example <?php // Create a 100*30 image $im = imagecreate(350, 30); // purple background and blue text $bg = imagecolorallocate($im, 150, 0,255); $textcolor = imagecolorallocate($im, 0, 0, 255); // Write the string at the top left imagestring($im, 5, 0, 0, 'Welcome to PHP GD Library Function!', $textcolor); $rotate = imagerotate($im,45,$bg); imagepng($rotate); ?> Output Figure 6.11 example of imagerotate() 6.1.14 imagepng() Outputs or saves a PNG image from the given image. Syntax bool imagepng ( resource $image [, string $filename [, int $quality]]) image An image resource, returned by one of the image creation functions, such as imagecolor() filename The path to save the file to. If not set or NULL, the raw image stream will be outputted directly. quality Compression level: from 0 (no compression) to 9. Example <?php $im = imagecreate(100,100); $bg=imagecolorallocate($im,0,0,255); imagepng($im); ?> imagepng() will save the info at $im (the image) in the file "image.png". Other image types may be created by using commands imagegif()-save file in gif format, imagewbmp() save file in wbmp format, imagejpeg() save file in jpeg format. 6.1.15 imagedestroy() imagedestroy() frees any memory associated with image image. Syntax bool imagedestroy ( resource $image ) image An image resource, returned by one of the image creation functions such as imagecreate() Returns TRUE on success or FALSE on failure Example <?php $im = imagecreate(100,100); $bg=imagecolorallocate($im,0,0,255); imagepng($im); imagedestroy($im); ?> 6.2 Regular expression in PHP Regular expressions are a powerful tool for examining and modifying text. Regular Expression commonly known as RegEx. Regular expressions themselves, with a general pattern notation almost like a mini programming language, allow you to describe and parse text. They enable you to search for patterns within a string, extracting matches flexibly and precisely. However, you should note that because regular expressions are more powerful, they are also slower than the more basic string functions. You should only use regular expressions if you have a particular need. The regular expression, as a pattern, can match all kinds of text strings helping your application validate, compare, compute, decide etc. It can do simple or very complex string manipulations. The list of possibilities is enormous when it comes to what you can achieve using regular expressions. You can take any phrase that starts with an "A" or any character and do various things with it. You can match phone numbers, email addresses, url's, credit card numbers, social security numbers, zip codes, states, cities.....(the list never ends). A huge script that is supposed to validate a user input and prepare it for sql can be reduced to only one line with the help of regular expression. Regular expressions started out as a feature of the Unix shell. They were designed to make it easier to find, replace and work with strings — and since their invention, they’ve been in wide use in many different parts of Unix based Operating Systems. They were commonly used in Perl, and since then have been implemented into PHP. Regular expression types There are 2 types of regular expressions POSIX Extended Perl Compatible The ereg, eregi, ... are the POSIX versions and preg_match, preg_replace, ... are the Perl version. It is important that using Perl compatible regular expressions (PCRE) the expression should be enclosed in the delimiters, a forward slash (/), for example. However this version is more powerful and faster as well than the POSIX one. The regular expressions basic syntax To use regular expressions first you need to learn the syntax of the patterns. We can group the characters inside a pattern like this Normal characters which match themselves like hello Start and end indicators as ^ and $ Count indicators like +,*,? Logical operator like | Grouping with {},(),[] A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched. Now let's see a detailed pattern syntax reference RegEx Match Not match Description (pattern) (subject) (subject) Match if the pattern is present anywhere world Hello world Hello Jim in the subject Match if the pattern is present at the ^world world class Hello world beginning of the subject Match if the pattern is present at the end world$ Hello world world class of the subject world/i This WoRLd Hello Jim Makes a search in case insensitive mode ^world$ world Hello world The string contains only the "world" worl, world, world* wor There is 0 or more "d" after "worl" worlddd world, world+ worl There is at least 1 "d" after "worl" worlddd worl, world, world? wor, wory There is 0 or 1 "d" after "worl" worly world{1} world worly There is 1 "d" after "worl" world, world{1,} worly There is 1 ore more "d" after "worl" worlddd world{2,3 worldd, world There are 2 or 3 "d" after "worl" } worlddd wo, world, wo(rld)* wa There is 0 or more "rld" after "wo" worldold earth|worl The string contains the "earth" or the earth, world sun d "world" w.rld world, wwrld wrld Any character in place of the dot. ^.{5}$ world, earth sun A string with exactly 5 characters [abc] abc, bbaccc sun There is an "a" or "b" or "c" in the string There are any lowercase letter in the [a-z] world WORLD string world, There are any lower- or uppercase letter in [a-zA-Z] WORLD, 123 the string Worl12 [^wW] \d \D \s earth w, W The actual character cannot be a "w" or "W" 123 abc Matches a digit character. abc 123 Matches a nondigit character. “ “(space) Abc, 123 Matches any whitespace character including space, tab, form-feed, etc. \S \w \W abc,123 “ “(space) Matches any non-whitespace character abc_xyz 123 Matches any word character including underscore 123 abc_xyz Matches any nonword character 6.2.1 Perl Compatible Regular Expression Perl-Compatible Regular Expressions emulate the Perl syntax for patterns, which means that each pattern must be enclosed in a pair of delimiters. Usually, the slash (/) character is used. For instance, /pattern/. The PCRE functions can be divided in several classes: matching, replacing, splitting and filtering preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. Syntax int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) $pattern pattern to search in string $subject input string, from which pattern will search $matches If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern. flags can set PREG_OFFSET_CAPTURE If this flag is set, for every occurring match the appending string with offset(index) will also be returned. we can specify the index from where start the search, by default it will start from index 0 $flag $offset Example <?php $subject = "abcdef"; $pattern = '/def/'; preg_match($pattern, $subject, $matches); print_r($matches); ?> Output Array ( [0] => def ) In above example preg_match() search pattern def in $Subject, $matches is array variable which stores array if pattern matches, above def is match from string “abcdef”, it will store matches part. ie “def”. <?php $subject = "defxyzdef"; $pattern = '/def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches); ?> Output Array ( [0] => Array ( [0] => def [1] => 6 ) ) In this example PREG_OFFSET_CAPTURE is specified means $matches array variable will store match pattern as well as index of that match above example [1]=>6 represents the index of the def from $subject. and last parameter offset is set 3 means Subject “defxyzdef” there are two matches by default it will search def with index 0, but we have specify the offset 3 so it will start search from position 3 and match def which is on index 6. preg_match_all() The preg_match_all() function matches all occurrences of pattern in string. After the first match is found, the subsequent searches are continued on from end of the last match, Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred. Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] ) $pattern $subject $matches $flag $offset pattern to search in string input string, from which pattern will search If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern. flags can set PREG_PATTERN_ORDER—(Default flag) Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on PREG_SET_ORDER --Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. PREG_OFFSET_CAPTURE--If this flag is set, for every occurring match the appending string with offset (index) will also be returned. we can specify the index from where start the search, by default it will start from index 0 Example <?php $subject = "defxyzdefabcdef"; $pattern = '/def/'; preg_match_all($pattern, $subject, $matches,PREG_PATTERN_ORDER); print_r($matches); ?> Output Array ( [0] => Array ( [0] => def [1] => def [2] => def ) ) In above example preg_match_all() matches all pattern from the string, $matches array variable will store match pattern as well as index of that match, PREG_PATTERN_ORDER will Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched. Now try same example with flag PREG_SET_ORDER. preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER); Output Array ( [0] => Array ( [0] => def ) [1] => Array ( [0] => def ) [2] => Array ( [0] => def ) ) PREG_SET_ORDER Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. Now try same example with flag PREG_OFFSET_CAPTURE preg_match_all ($pattern, $subject, $matches, PREG_OFFSET_CAPTURE ) Ouptut Array ( [0] => Array ( [0] => Array ( [0] => def [1] => 0 ) [1] => Array ( [0] => def [1] => 6 ) [2] => Array ( [0] => def [1] => 12 ) ) ) PREG_OFFSET_CAPTURE return every occurring match the appending string with offset (index) will also be returned. preg_replace() preg_replace() search and replace the string, Searches subject for matches to pattern and replaces them with replacement, preg_replace() returns an array if the subject parameter is an array, or a string otherwise. If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred. Syntax mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) $pattern The pattern to search for $replacement The string or an array with strings to replace $subject The string or an array with strings to search and replace. If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well. $limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). count If specified, this variable will be filled with the number of replacements done Example <?php $num = 4; $string = "This string has four words."; $string = preg_replace('/four/', $num, $string); echo $string; ?> Output This string has 4 words. In above example it will search pattern four and replace with 4 in $string. Example <?php $string = '2007-01-15'; $pattern = '/(\d+)-(\d+)-(\d+)/';\\ \d represents number only so pattern match with string $replacement = '$2/$3/$1'; echo preg_replace($pattern, $replacement, $string); //$0 will represent the whole string ?> Output 01/15/2007 In above example replacement may contain references of the form \\n or $n. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. so as per our example $0 represents whole string, $1 represents 2007 and $3 represents 15, '$2/$3/$1' using this replacement we are changing the order of the string and adding “/” instead of “–“. Example <?php $count = 0; echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count); echo $count; //3 ?> Ouput xp***to3 In above example pattern search for \d,\s mean numbers and white space will search, it will replace number and space into *, -1 represents limit by default is -1 indicating the maximum possible replacement is to do. $count will return number of replacement has done. so it return 3. Example <?php $count = 0; $a=preg_replace(array('/\d/', '/\s/'), '*', array('xp 4 to','he ll o'), 3 , $count); print_r($a); echo $count; //3 ?> Output Array ( [0] => xp***to [1] => he*ll*o ) 5 In this example subject is an array so preg_replace will return array. preg_split() Split the given string by a regular expression, Returns an array containing substrings of subject split along boundaries matched by pattern. Syntax array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] ) pattern The pattern to search for, as a string. subject limit flags The input string. If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0 or null means "no limit. flag can set following possibilities. PREG_SPLIT_NO_EMPTY-If this flag is set, only non-empty pieces will be returned by preg_split(). PREG_SPLIT_OFFSET_CAPTURE - If this flag is set, for every occurring match the appending string with offset (index) will also be returned. Example <?php $string = "aBBBaCCCADDDaEEEaGGGA"; $chunks = preg_split ("/a/", $string, 5); print_r($chunks); ?> Output Array ( [0] => [1] => BBB [2] => CCCADDD [3] => EEE [4] => GGGA ) In above example pattern will search “a” in string, wherever preg_split find a it start spilting process. Same example with flag PREG_SPLIT_NO_EMPTY, it will remove all empty pieces from preg_split returns $chunks = preg_split ("/a/", $string, 5,PREG_SPLIT_NO_EMPTY); Output Array ( [0] => BBB [1] => CCCADDD [2] => EEE [3] => GGGA ) preg_gerp() preg_grep function is similar to pre_match() it will match the pattern, but preg_match will only search pattern in string where as preg_grep will search pattern in array, and it will returns the array consisting of the elements of the input array that match the given pattern. Syntax array preg_grep ( string $pattern , array $input [, int $flags = 0 ] ) pattern input flags The pattern to search for, as a string. The input array. If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern. Example <?php $n=array('john','partric','amy'); $result=preg_grep('/^[a-m]/',$n); print_r($result); ?> Output Array ( [0] => john [2] => amy ) In above program preg_grep first match the pattern ^ represents starting of the string, so stastring must be in between small a-m so it match john and amy. Same example with flag PREG_GREP_INVERT, it will return opposite of preg_grep search $result=preg_grep('/^[a-m]/',$n, PREG_GREP_INVERT); Output Array ( [1] => partric ) preg_quote() preg_quote() takes string and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters. and it returns the quoted string. Syntax string preg_quote ( string $str [, string $delimiter = NULL ] ) str delimiter The input string. If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter. Example <?php $keywords = '$40 for a g3/400'; $keywords = preg_quote($keywords, '/'); echo $keywords; // returns \$40 for a g3\/400 ?> Output \$40 for a g3\/400 6.2.2 POSIX Regular Expression ereg() ereg() function is similar to preg_match(), preg_match() was PCRE functions, while ereg() is PSOIX function which searches a string for matches to the regular expression given in pattern in a case-sensitive way, Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred. Syntax int ereg ( string $pattern , string $string [, array &$regs ] ) pattern Case sensitive regular expression. string The input string. regs If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis. $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched. Example <?php $zip = "[0-9]{5}"; $str = "Mission Viejo, CA 92692"; ereg($zip,$str,$regs); print_r ($regs); ?> Output Array ( [0] => 92692 ) In above example [0-9]({5} indicates any number of 5 digits will search in string if found it will stores $regs array variable. eregi() This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters. eregi() function returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred Syntax int eregi ( string $pattern , string $string [, array &$regs ] ) pattern Case insensitive regular expression. string The input string. regs If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis. $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched. Example <?php $string = 'XYZ'; if (eregi('z', $string)) { echo "'$string' contains a 'z' or 'Z'!"; } ?> Output 'XYZ' contains a 'z' or 'Z'! ereg_replace() This function scans string for matches to pattern, and then replaces the matched text with replacement. Its return the modified string is returned. If no matches are found in string, then it will be returned unchanged string. Syntax string ereg_replace ( string $pattern , string $replacement , string $string ) pattern pattern to match replacement The string which to replace string The input string Example <?php $num = '4'; $string = "This string has four words."; $string = ereg_replace('four', $num, $string); echo $string; ?> Output This string has 4 words In above example $num datatype is string ie ‘4’ because if 4 is there (integer datatype) then it will return unchanged string because according to syntax replacement must be string. eregi_replace() This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters. Syntax string eregi_replace ( string $pattern , string $replacement , string $string ) pattern pattern to match replacement The string which to replace string The input string Example <?php $num = '4'; $string = "This string has four words."; $string = ereg_replace('FOUR', $num, $string); echo $string; ?> Output This string has 4 words split() Splits a string into array by regular expression, and it returns an array of strings by the casesensitive regular expression pattern. Syntax array split ( string $pattern , string $string [, int $limit = -1 ] ) pattern string limit pattern to search in Case sensitive. The input string. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. Example <?php $string = "ABBBaCCCADDDAEaEaGGGA"; $chunks = split ("a", $string,2); print_r($chunks); ?> Output Array ( [0] => ABBB [1] => CCCADDDAEaEaGGGA ) In above example it will start splitting when pattern found “a” and limit is specify 2 so it return 2 elements and rest whole string in last element and it will search case sensitive. spliti() This function is identical to split() except that this ignores case distinction when matching alphabetic characters. , and it returns an array of strings by the case-insensitive regular expression pattern. Syntax array spliti ( string $pattern , string $string [, int $limit = -1 ] ) pattern string limit pattern to search in Case insensitive. The input string. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. Example <?php $string = "ABBBaCCCADDDAEaEaGGGA"; $chunks = spliti ("a", $string,5); print_r($chunks); ?> Output Array ( [0] => [1] => BBB [2] => CCC [3] => DDD [4] => EaEaGGGA ) In above example it will start splitting when pattern found “a” or “A” and limit is specify 5 so it return 5 elements and rest whole string in last element and it will search case insensitive and it will not include “a” or “A” in output because it will start splitting from “a” or “A”. 6.3 Cookies A cookie is a text file used to represent a user of the website. Cookie is stored on the local computer of the user. When you visit a website a cookie may be set to represent the user. Next time he visits the website, he does not need to identify himself manually; instead the cookie will represent him on that website. With the help of PHP, cookies can be created, read and destroyed. The main difference between a session and a cookie is that cookies are stored on the user’s computer where as sessions are stored on the server for particular usage. Cookies can be manually deleted by the users also to make sure security is not breached. Use of cookies We can literally put 4000 characters of data in a text cookie file and store information about the user preferences for a particular website. Some of the practical uses of Cookies are as follows Many sites use them to provide customized pages and results to their users. This can be achieved by storing all the information like preferences etc in a cookie. Many websites use cookies to log their users in automatically. By storing a few pieces of user information they can automatically authenticate the user's details and use them to save the user time when they log in. Visitor tracking and statistics systems often use them to track visitors. By assigning the visitor a cookie, they will not be counted more than once, so accurate unique visitor statistics can be obtained. Cookie Security Cookie is just a flat text file, it can be opened and read on the computer it is stored in. If a website has stored a password in a cookie it can be read and but if the same password is encrypted using a hash like md5 () or sha1 () then it can be more secure since this content is used to match it with the password stored on the website. Set a Cookie In PHP, we have a function setcookie() which is used to SET as well as UNSET the cookie. The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie("name", "value", expire, "path", "domain"); Name: Value: Expire: Path: Domain: it’s the name of the cookie the value that is to be stored in the cookie. Ex: username, password, email id it’s the expiring time of the cookie since it was set. the path of the website where the cookie is valid. Like a subdomain The website this cookie is valid for. Example <?php setcookie("username", "XYZ", time()+3600); ?> In the above example, the Cookie name is username. value is XYZ, it expires in 1 hour. It is mentioned in seconds 60 seconds multiplied by 60 minutes. How to Retrieve a Cookie Value PHP comes with a super global $_COOKIE. All cookies set by a website on their clients website is retrieved via this super global. Example <?php if (isset($_COOKIE["username"])) { echo $_COOKIE["username"];// Print a cookie print_r($_COOKIE); // A way to view all cookies } else echo "Cookie not created"; ?> Ouput XYZArray ( [username] => XYZ ) The above script checks if the cookie with the name username is set. If it is set it prints the cookie. If the cookie is not set then are just prints out cookie not created Delete a Cookie There is no special function to delete a cookie. It can be done by reversing the timing of expiry in the cookie by resetting it again as shown below setcookie("username", "", time()-3600); From the above statement, if you observe the name of the cookie is the same as it was set. The value of the cookie is set to NULL and the expiry time is subtracted from the current time to 1 hour earlier making it to expire at the moment the above function is run. Example <?php // set the expiration date to one hour ago setcookie("username", "", time()-3600); ?> So this way we can create, retrieve and delete the cookie. if we want to see the cookie created we can and we can open cookie in any text editor, to view cookie Start Runcookie and press enter it will open folder named cookie, there you can view cookies created as text file. 6.4 Session Sessions are used to store information which can be used through-out the application for the entire time the user is logged in or running the application. Each time a user visits your website, you can create a session for that user to store information pertaining to that user. Unlike other applications, in web applications, all the stored variables and objects are not globally available throughout all pages (unless sent through POST or GET methods to the next page), so to tackle this problem sessions are utilized. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL. Create Session in PHP In PHP, information is stored in session variables. Now let’s learn how we create a session in PHP, before you can store any information in session variables, you must first start up the session using the session_start() function. See below Example <?php session_start(); ?> <html> <body> --------------------------------</body> </html> When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the session id using the PHP predefined constant PHPSESSID. The code above starts a session for the user on the server, and assigns a session id for that user's session. Storing information in session To store information is a session variable, you must use the predefined session variable $_SESSION.its create an associative array, using this you can store and retrieve session data. Example <?php session_start(); $_SESSION['name'] = "Ronak"; // store session data $_SESSION['age']="23"; echo "name=". $_SESSION['name']; echo "<br>"; echo "age=". $_SESSION['age']; ?> Output name=Roank age=23 Destroying Session Sessions are destroyed automatically after user leaves your website or closes the browser, but if you wish to clear a session variable yourself, you can simple use the unset() function to clean the session variable or the session_destroy() function unset() unset() function is used to free the specified session variable Example <?php session_start(); $_SESSION['name'] = "Ronak"; // store session data $_SESSION['age']="23"; echo "name=". $_SESSION['name'];//retrieve the session value print Ronak echo "<br>"; echo "age=". $_SESSION['age'];//print 23 echo "<br>" unset($_SESSION['age']);//destroy session=age echo "name=". $_SESSION['name'];//print Ronak echo "<br>"; echo "age=". $_SESSION['age'];// print nothing because session is destroyed ?> Ouput name=Ronak age=23 name=Ronak age= session_destroy() session_destroy() will reset your session and you will lose all your session data. Example <?php session_start(); session_destroy(); echo "name=". $_SESSION['name']; echo "age=". $_SESSION['age']; ?> Output name=Ronak age=23 Above example if session_destroy() is used then also it will print the session variable. because session_destroy() will not remove the session until session is in use. when session will get free at that time it will remove all session variable.try to refresh and run it will print name= age= all session will destroy. 6.5 Server Variable Server Variables are those variables which are inside the super global array named $_SERVER available in PHP. There are many server variables in PHP and some of them are very useful for developing PHP projects. All servers maintain a set of variables that provide information such as where the user come from, and other useful information. You can access these variables by name in PHP. The $_SERVER variable is an associative array that you could iterate using the foreach construct. The following example lists each of the variables, and the associated value. example will list out all server variable. Example <?php foreach($_SERVER as $key=>$value) print $key . " = " . $value . "<br>"; ?> Output DOCUMENT_ROOT = C:/xampp/htdocs SERVER_ADMIN = postmaster@localhost SCRIPT_FILENAME = C:/xampp/htdocs/xampp/test.php SERVER_PROTOCOL = HTTP/1.1 REQUEST_METHOD = GET QUERY_STRING = REQUEST_URI = /xampp/test.php SCRIPT_NAME = /xampp/test.php In above example listed few of the server variable, let’s see variable and description of variable in detail. Server Variable Description PHP_SELF The filename of the currently executing script,relative to document root SERVER_NAME The name of the server host under which the current script is SERVER_ADDR SERVER_SOFTWARE SERVER_PROTOCOL REQUEST_METHOD REQUEST_TIME QUERY_STRING DOCUMENT_ROOT HTTP_ACCEPT HTTP_ACCEPT_CHAR SET HTTP_ACCEPT_LANG UAGE HTTP_HOST' HTTP_USER_AGENT HTTPS REMOTE_ADDR REMOTE_HOST REMOTE_PORT SCRIPT_FILENAME SERVER_ADMIN SERVER_PORT SCRIPT_NAME REQUEST_URI PHP_AUTH_USER PHP_AUTH_PW PATH_INFO executing The IP address of the server under which the current script is executing. Server identification string, given in the headers when responding to requests Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0'; Which request method was used to access the page; i.e. 'GET', 'POST'. The timestamp of the start of the request The query string, if any, via which the page was accessed. The document root directory under which the current script is executing, as defined in the server's configuration file. Contents of the Accept: header from the current request, if there is one Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'. Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'. Contents of the Host: header from the current request, if there is one. Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Set to a non-empty value if the script was queried through the HTTPS protocol. The IP address from which the user is viewing the current page The Host name from which the user is viewing the current page The port being used on the user's machine to communicate with the web server The absolute pathname of the currently executing script The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file The port on the server machine being used by the web server for communication. For default setups, this will be '80'; Contains the current script's path The URI which was given in order to access this page; for instance, '/index.html' When doing HTTP authentication this variable is set to the username provided by the user When doing HTTP authentication this variable is set to the password provided by the user. Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. 6.6 Database Connectivity with MySQL (using PhpMyAdmin) MySQL and PHP are two technologies used by many web developers. Connecting to MySQL from PHP is easy and when we consider that both PHP and MySQL are free technologies, the pair sounds like winning choice. MYSQL is open source database. The data in MySQL is stored in database object called tables. A table is collection of rows and columns. Databases are useful when storing information categorically. A company may have a database with the following tables "Employees", "Products", "Customers" and "Orders". We are going to connect PHP and MySQL with help of PhpMyAdmin, PhpMyAdmin is nothing but a software which manage MySQL database, tables, how to alter table, add fields, insert records, backup table and backup database. phpMyAdmin is an open source php script. Download phpMyAdmin from www.phpmyadmin.net and unzip it in "htdocs" directory. Or else when you use XAMPP or WAMPP software for PHP, it also provide us phpMyAdmin also, in that case no need to install separate phpMyAdmin. Now we will see how to connect PHP and MySQL, steps will be same for XAMPP or simple phpMyAdmin Start your browser and type in the Address http://localhost/phpMyAdmin/ phpMyAdmin home page displays Figure 6.12 home page of phpmyadmin Create new database Student, type name of database and click create button Figure 6.13 Create database it will give message that database Student has been created. Now create new table in database Student. Figure 6.14 Create table Table Created named as stud with number of fields 5 Now it will ask you to enter fields information such as field name, datatype, length, default value etc. Field name will be no, Fname, Mname, Lname, semester. Figure 6.15 display table field information Click Save button. Table created Figure 6.16 Table Successfully created Here you can edit table fields. Click a pencil icon and change a field name or an attribute. If you want to delete a field click X icon. Click Insert link to insert data in the student table. Table fields display for data entry. Enter your values. Figure 6.17 insert the fields in table stud Click Go button. Click Browse link. Inserted records display Figure 6.16 Table Successfully created Figure 6.18 Clicking on Browse button view entered data Click SQL link. SQL text area displays for SQL query. Edit query SELECT * FROM `stud` WHERE Fname='Hetal' And press Go button. Found record displays. Figure 6.19 SQL Search record displays So this way database and table is created in phpMyAdmin and now let’s see how to do coding in php for adding, inserting, deleting and updating records from the database Student. Connect your Database Before we can access data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function. mysql_connect() mysql_connect() creates a connection to the database, Returns a MySQL link identifier on success or FALSE on failure. Syntax mysql_connect(servername,username,password); servername Optional. Specifies the server to connect to. Default value is "localhost"( localhost is the MySQL server which usually runs on the same physical server as your script). username Optional. Specifies the username to log in with. Default value “root” for phpmyadmin password Optional. Specifies the password to log in with. Default is "" Example <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?> mysql_close() The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function. mysql_close return true on success false on failure. Syntax bool mysql_close ([ resource $link_identifier ] ) $link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() Example <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_close($con); ?> mysql_select_db() The mysql_select_db() function sets the active MySQL database. This function returns TRUE on success, or FALSE on failure. Syntax mysql_select_db(database,connection) database Required. Specifies the database to select. connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() is used. Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student", $con); if (!$db_selected) { die ("Can\'t use Student : " . mysql_error()); } mysql_close($con); ?> Insert Data into a Database Table The INSERT INTO statement is used to add new records to a database table. Syntax It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values INSERT INTO table_name VALUES (value1, value2, value3,...) The second form specifies both the column names and the values to be inserted INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...) To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. mysql_query() The mysql_query() function executes a query on a MySQL database. This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure. Syntax mysql_query(query,connection) query Specify the query to send connection Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() is used. Example <?php $con = mysql_connect("localhost","root",""); //open connection if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Student", $con); //select database //insert records in database student and table stud with help of insert query mysql_query("INSERT INTO stud(no,Fname, Mname, Lname, semester) VALUES (3, 'Jayna','hardik','Rupani',1)"); //mysql_query() execute the query mysql_query("INSERT INTO stud(no,Fname, Mname, Lname, semester) VALUES (4, 'Hetal','Tarun','bhesdadiya',3)"); echo "2 records added"; mysql_close($con); //close connection ?> Ouput echo 2 records added And now if you wish to see in database open phpmyadmin and select the database student and table stud Figure 6.20 Example of insert record through query string 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 To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection and fetch records from recordset there are four different way let’s see one by one. mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_fetch_row mysql_fetch_array() The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a numeric array. This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows. After the data is retrieved, this function moves to the next row in the recordset. Each subsequent call to mysql_fetch_array() returns the next row in the recordset. Syntax mysql_fetch_array(data,array_type) data array_type Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function Optional. Specifies what kind of array to return. Possible values •MYSQL_ASSOC - Associative array •MYSQL_NUM - Numeric array •MYSQL_BOTH - Default. Both associative and numeric array Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud"; $result = mysql_query($sql,$con); print_r(mysql_fetch_array($result, MYSQL_BOTH)); mysql_close($con); ?> Output Array ( [0] => 1 [no] => 1 [1] => sheetal [Fname] => sheetal [2] => Chandrakant [Mname] => Chandrakant [3] => Rakangor [Lname] => Rakangor [4] => 3 [semester] => 3 ) In above example mysql_fetch_array() fetch first record from recordset and print array as associative array as well as numeric array. Associative array means Fname field name of table will treat as index of associative array, numeric array index will start from 0. now if want only numeric array you can write like print_r(mysql_fetch_array($result, MYSQL_NUM)); same example only this change will return only return numeric array, by default it will return both numeric as well as associative array. If user want associative array as output we can make change in above example, it will return associative array only. print_r(mysql_fetch_array($result, MYSQL_ASSOC)); mysql_fetch_assco() The mysql_fetch_assoc() function returns a row from a recordset as an associative array. This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows. After the data is retrieved, this function moves to the next row in the recordset. Each subsequent call to mysql_fetch_assoc() returns the next row in the recordset. Syntax mysql_fetch_assoc(data) data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud"; $result = mysql_query($sql,$con); print_r(mysql_fetch_assoc($result)); mysql_close($con); ?> Output Array ( [no] => 1 [Fname] => sheetal [Mname] => Chandrakant [Lname] => Rakangor [semester] => 3 ) mysql_fetch_object() The mysql_fetch_object() function returns a row from a recordset as an object. This function gets a row from the mysql_query() function and returns an object on success, or FALSE on failure or when there are no more rows. Each subsequent call to mysql_fetch_object() returns the next row in the recordset Syntax data mysql_fetch_object(data) Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud"; $result = mysql_query($sql,$con); print_r(mysql_fetch_object($result)); mysql_close($con); ?> Output stdClass Object ( [no] => 1 [Fname] => sheetal [Mname] => Chandrakant [Lname] => Rakangor [semester] => 3 ) mysql_fetch_row() The mysql_fetch_row() function returns a row from a recordset as a numeric array. This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows. After the data is retrieved, this function moves to the next row in the recordset Syntax mysql_fetch_row(data) data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud where Fname='sheetal'"; $result = mysql_query($sql,$con); print_r(mysql_fetch_row($result)); mysql_close($con); ?> Output Array ( [0] => 1 [1] => sheetal [2] => Chandrakant [3] => Rakangor [4] => 3 ) Display result in HTML format Above example we have seen how we can fetch records from recordset but we were getting first record or only one record depending on the query we fired, now if we want record in HTML table format <table> tag is used and while loop is used to access all the records from the recordset. Example <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Student", $con); $result = mysql_query("SELECT * FROM stud"); echo "<table border='1'> <tr> <th>no</th> <th>Fname</th> <th>Mname</th> <th>Lname</th> <th>Semester</th> </tr>"; while($row = mysql_fetch_array($result)) //fetch one by one record { echo "<tr>"; echo "<td>" . $row['no'] . "</td>"; echo "<td>" . $row['Fname'] . "</td>"; echo "<td>" . $row['Mname'] . "</td>"; echo "<td>" . $row['Lname'] . "</td>"; echo "<td>" . $row['semester'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> Ouput no 1 2 3 4 Fname sheetal Hetal Jayna Hetal Mname Chandrakant Navin bhai hardik Tarun Lname Semester Rakangor 3 Timbadiya 3 Rupani 1 bhesdadiya 3 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 Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql=("UPDATE stud SET semester = 4 WHERE Fname = 'Hetal' and Mname='tarun' "); //Update record where fname=hetal and mname=tarun $result = mysql_query($sql,$con); echo ("Number of rows affected" . mysql_affected_rows()."<br>"); //number of rows affected $sql1="Select * from stud where Mname='tarun' "; $result = mysql_query($sql1,$con); print_r(mysql_fetch_row($result)); mysql_close($con); ?> Output Number of rows affected1 Array ( [0] => 4 [1] => Hetal [2] => Tarun [3] => bhesdadiya [4] => 4 ) In above example record will update field semester=4 where fname=hetal there are two records where fname=hetal so mname=tarun is check, mysql_affected_rows() function return number of rows affected by last query executed. mysql-affected_rows() The mysql_affected_rows() function returns the number of affected rows in the previous MySQL operation. This function returns the number of affected rows on success, or -1 if the last operation failed Syntax mysql_affected_rows(connection) connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() is used. Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql=("UPDATE stud SET semester = 5 WHERE Fname = 'Hetal' "); $result = mysql_query($sql,$con); echo ("Number of rows affected" . mysql_affected_rows()."<br>"); mysql_close($con); ?> Output Number of rows affected2 In above example we have two records having Fname=’Hetal’ so will change the field semester =5 in two records and mysql_affected_rows() return 2 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 Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted Example <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Student", $con); mysql_query("DELETE FROM stud WHERE Mname='tarun'"); echo ("Number of rows affected " . mysql_affected_rows()."<br>"); mysql_close($con); ?> Output Number of rows affected 1 PHP MySQL Function There are many functions for MySQL using which we can get the database, table’s information in PHPscript. Let’s see few of them. mysql_error() The mysql_error() function returns the error description of the last MySQL operation. This function returns an empty string ("") if no error occurs. Syntax mysql_error(connection) Connection Optional argument specify the MySql Connection Example <?php $con = mysql_connect("localhost","wrong_user","wrong_pwd"); if (!$con) { die(mysql_error()); } mysql_close($con); ?> Output Access denied for user 'wrong_user'@'localhost' (using password: YES) mysql_errno() The mysql_errno() function returns the error number of the last MySQL operation. This function returns 0 (zero) if no error has occurred Syntax mysql_errno(connection) Connection Optional argument specify the MySql Connection Example <?php $con = mysql_connect("localhost","wrong_user","wrong_pwd"); if (!$con) { die('Could not connect: ' . mysql_errno()); } mysql_close($con); ?> Output Could not connect: 1045 mysql_data_seek() The mysql_data_seek() function moves the internal row pointer. The internal row pointer is the current row position in a result returned by the mysql_query() function. This function returns TRUE on success, or FALSE on failure. Syntax data row mysql_data_seek(data,row) Required. Specifies which data pointer to use. Required. Specifies which record to move to. 0 indicates the first record Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud "; $result = mysql_query($sql,$con); print_r(mysql_fetch_row($result)); //Return first record mysql_data_seek($result,2); //move internal pointer to record 3 having index 2 print_r(mysql_fetch_row($result)); // Return third record mysql_close($con); ?> Output Array ( [0] => 2 [1] => Hetal [2] => Navin bhai [3] => Timbadiya [4] => 5 ) Array ( [0] => 4 [1] => Khevna [2] => D [3] => Chhaya [4] => 3 ) mysql_fetch_lengths() The mysql_fetch_lengths() function returns the length of the contents of each field in a row. The row is retrieved by mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_object(), or mysql_fetch_row().mysql_fetch_legths() count the number of character enter in the field. This function returns a numeric array on success, or FALSE on failure or when there are no more rows. Syntax mysql_fetch_lengths(data) data Required. Specifies which data pointer to use. Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud WHERE Lname='Chhaya'"; $result = mysql_query($sql,$con); print_r(mysql_fetch_row($result)); print_r(mysql_fetch_lengths($result)); mysql_close($con); ?> Output Array ( [0] => 4 [1] => Khevna [2] => D [3] => Chhaya [4] => 3 ) Array ( [0] => 1 [1] => 6 [2] => 1 [3] => 6 [4] => 1 ) mysql_num_rows() The mysql_num_rows() function returns the number of rows in a recordset. This function returns FALSE on failure. Syntax mysql_num_rows(data) data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function Example <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("Student",$con); $sql = "SELECT * from stud"; $result = mysql_query($sql,$con); echo mysql_num_rows($result); mysql_close($con); ?> Output 3 There are total three records in database table stud it return 3 Three are certain function which gives information regarding fields of the table let’s see overview of them. Below is the list of function used for getting information regarding fields of table Function Description Example mysql_field_flags() Returns information $sql = "SELECT * from stud"; regarding flags set, while $result = mysql_query($sql,$con); creating table. like $flags = mysql_field_flags($result, 0); primary_key mysql_field_len() Returns the maximum length of a field in a recordset. while creating table we specify the length that will return mysql_field_name() Function returns the name of a field in a recordset echo $flags; $sql = "SELECT * from stud"; $result = mysql_query($sql,$con); $len = mysql_field_len($result, 0); echo $len //25 $sql = "SELECT * from stud"; $result = mysql_query($sql,$con); $name = mysql_field_name($result, 0); echo $name //Fname mysql_fetch_field() Function returns an $sql = "SELECT * from stud"; object containing $result = mysql_query($sql,$con); information of a field print_r( mysql_fetch_field($result)); from a recordset. mysql_field_seek() Jumps to specified fields $sql = "SELECT * from stud"; in a recordset e.g.specify $result = mysql_query($sql,$con); 2 means jump to field mysql_field_seek($result,2); third print_r(mysql_fetch_field($result)); mysql_num_fields() function returns the $sql = "SELECT * FROM stud"; number of fields in a $result = mysql_query($sql,$con); recordset echo mysql_num_fields($result); //5 eg //no,fname,mname,lname,semester mysql_field_table() function returns the $sql = "SELECT * from Person"; name of the table where $result = mysql_query($sql,$con); a specified field is $table = mysql_field_table($result, 0); located echo $table; mysql_field_type() function returns the type $sql = "SELECT * from Person"; of a field in a recordset. $result = mysql_query($sql,$con); $type = mysql_field_type($result,1);//Fname echo $type; //Return String Insert, Update, and Delete Data from a Form into a Database If user wants to insert, update and delete data from a HTML form into a database is possible and this will be user friendly. Its like mini project, I have created database Student and table stud with 5 fields no, Fname, Mname, Lname, and semester and created four .php file using which we can perform operation like add, update, delete and view records in table format. To view records in table format as well as link’s is given for add, update and delete records in connection3.php file. so let’s start from connection3.php file. Example connection3.php <html> <head> <title> Adding a row to a table</title> </head> <body> <?php $user = "root"; $pass = ""; $db = "Student"; $link = mysql_connect( "localhost", $user, $pass ); if ( ! $link ) die( "Couldn't connect to MySQL" ); mysql_select_db($db, $link ); $result = mysql_query( "SELECT * FROM stud" ); $num_rows = mysql_num_rows($result); //Return total number of records in recordset print "There are currently $num_rows rows in the table<P>"; print "<table border=1>\n"; while ( $a_row = mysql_fetch_row( $result ) ) { print "<tr>\n"; foreach ( $a_row as $field ) print "\t<td>$field</td>\n"; print "<td><a href='edit.php?Fname=".$a_row[1]."'>Update</a></td>"; print "<td><a href='delete.php?Fname=".$a_row[1]."'>Delete</td>"; print "</tr>\n"; } print "</table>\n"; print "<a href='add.php'>add a new record</a>\n"; mysql_close( $link ); ?> </body> </html> Output There are currently 3 rows in the table 1 sheetal Chandrakant Rakangor 3 Update Delete 2 Hetal Navin bhai Timbadiya 5 Update Delete 3 Jayna hardik Rupani 1 Update Delete add a new record Above example will return all records from table stud and added three links like add a new record, update and delete record. Now let’s add new record by clicking add a new record it will call add.php file Example add.php <html> <head></head> <body> <?php $user = "root"; $pass = ""; $db = "Student"; $link = mysql_connect( localhost, $user, $pass ); if ( ! $link ) die( "Couldn't connect to MySQL" ); mysql_select_db($db, $link ); ?> <form method="post"> Roll Number <input type="text" name="no" /><br /> Firstname: <input type="text" name="fn" /><br /> Middlename: <input type="text" name="mn" /><br /> Lastname: <input type="text" name="ln" /><br /> Semester <input type="text" name="sem" /><br /> <input type="submit" value="submit" name="add"/><br /> </form> <?php if (isset($_POST['add'])) { $sql="INSERT INTO stud (no,Fname, Mname,Lname,Semester) VALUES ('$_POST[no]','$_POST[fn]','$_POST[mn]','$_POST[ln]','$_POST[sem]')"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } print "<h1>Sucessfully Added ". mysql_affected_rows() ." row</h1><p>"; include("connection3.php"); } ?> </body> </html> Output Figure 6.21 add records using html form Once user click submit button it will add record and call connection3.php file it will list out all the records and give output like this Figure 6.22 added record in table format Now let’s update the record by clicking the link Update, it will call edit.php file, which record you want to update suppose I have selected 1 record Update link then it will call edit.php?Fname=Sheetal and pass Fname=Sheetal on that bases update query will fired. Example edit.php <?php $user = "root"; $pass = ""; $db = "Student"; $link = mysql_connect( "localhost", $user, $pass ); if ( ! $link ) die( "Couldn't connect to MySQL" ); mysql_select_db("Student", $link ); $fn=$_REQUEST['Fname']; $result=mysql_query("select * from stud where Fname='$fn'"); // Split records in $result by table rows and put them in $row. $row=mysql_fetch_assoc($result); // Close database connection. ?> <form method="post"> Roll Number <input type="text" name="no" /><br /> Firstname: <input type="text" name="fn" /><br /> Middlename: <input type="text" name="mn" /><br /> Lastname: <input type="text" name="ln" /><br /> Semester <input type="text" name="sem" /><br /> <input type="submit" value="submit" name="edit"/> </form> </body> </html> <?php if (isset($_POST['edit'])) { $sql="UPDATE stud set no='$_POST[no]',Fname='$_POST[fn]',Mname='$_POST[mn]',Lname='$_POST[ln]', semester='$_POST[sem]' where Fname='$fn' "; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } print "<h1>Sucessfully Updated ". mysql_affected_rows() ." row</h1>"; include("connection3.php"); } ?> Output Figure 6.23 example of edit record edit.php now ask user to update the record where Fname=Sheetal, I have made the changes and now click submit button it will call connection3.php file it show us the changes made to it Figure 6.24 successfully record Updated Now let’s delete a record when user click on delete link it will Delete the record from the database and call delete.php file, let’s delete first record it will call delete.php?Fname=’Sheetal’ Example delete.php <?php $user = "root"; $pass = ""; $db = "Student"; $link = mysql_connect( "localhost", $user, $pass ); if ( ! $link ) die( "Couldn't connect to MySQL" ); mysql_select_db("Student", $link ); $fn=$_REQUEST['Fname']; // Do delete statement. $result=mysql_query("delete from stud where Fname='$fn'"); if ( ! $result ) die('Error: ' . mysql_error()); else echo "Deleted sucessfully <BR>"; // Close database connection mysql_close(); include("connection3.php"); ?> Output Deleted sucessfully There are currently 3 rows in the table 2 Hetal Navin bhai Timbadiya 5 Update Delete 3 Jayna hardik Rupani 1 Update Delete 4 Khevna D Chhaya 3 Update Delete add a new record This way you can add, update and delete the records using HTML form and table tag.