Contenu connexe


PHP and MySQL with snapshots

  1. PHP By: Kunika Verma
  2. Introduction PHP is an acronym for "PHP Hypertext Preprocessor“. PHP is a widely-used, open source scripting language. PHP scripts are executed on the server. PHP costs nothing, it is free to download and use. PHP is simple for beginners. PHP also offers many advanced features for professional programmers. What is a PHP File? PHP files can contain text, HTML, CSS, JavaScript, and PHP code. PHP code are executed on the server, and the result is returned to the browser as plain HTML. PHP files have extension ".php“.
  3. Why PHP PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP supports a wide range of databases. PHP is free. Download it from the official PHP resource: PHP is easy to learn and runs efficiently on the server side. How to run PHP files? localhost/foldername/filename Resource: Xampp  Combines an Apache web server, PHP, and MySQL into one simple installation service.  Very little configuration required by the user to get an initial system up and running. 
  4. Variables in PHP
  5. Variables in PHP Variables in PHP are denoted by a dollar ($) sign followed by the name of the variable. Variable names are case sensitive ($y and $Y are two different variables). A variable name cannot start with a number. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  6. Example Usage of Variables
  7. Output:
  8. Arrays in PHP
  9.  An array can store one or more values in a single variable name. Each element in the array is assigned its own ID so that it can be easily accessed. $array[key] = value; An array in PHP is a structure which maps keys to values . The keys can specified explicitly or they can be omitted. If keys are omited, integers starting with 0 are keys. The value mapped to a key can, itself, be an array, so we can have nested arrays.
  10. Types of Arrays
  11. Numeric Array An Array with numeric index. A numeric array stores each element with a numeric ID key. Automatically array: Example: $names = array("Peter","Quagmire","Joe");
  12. Manually array <?php $lang[0]="PHP"; $lang[1]="Perl"; $lang[2]="Java"; $lang[3]=".Net"; echo "<b>" .$lang[0]. " and " .$lang[1]. " are programming languages."; ?>
  13. Associative Array An array where each ID key is associated with a value. An array with strings index. This stores element values in association with key values rather than in a strict linear index order. When storing data about specific named values, a numerical array is not always the best way to do it. It is the combination of keys and values. Associative array will have their index as string so that you can establish a strong association between key and values. Syntax: $arr_name=array(“key”=>value, “key”=>value);
  14. Example: <?php $lang ['php']="10"; $lang ['perl']="5"; $lang ['java']="2"; echo "php language is ".$lang ['perl']. "years old."; ?>
  15. Multidimensional Array An array containing one or more array. In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Syntax: $ main_Array=array ( “sub-array=>array( “PHP”, “perl” ) );
  16. Example: <?php $array=array( "php"=>array( "php1", "php", "php5" ), "perl"=>array( "perl5" ) ); echo "<b>". "Is " . $array ["perl"] [0] . " programming language?"; ?>
  17. Array-manupulation functions PHP provides a huge set of array-manipulation functions. Some of them are given below: array -- Create an array Mixed_array –integers and strings current_array-Return the current elements in the array array_key_exists -- Checks if the given key or index exists in the array array_keys -- Return all the keys of an array array_merge -- Merge two or more arrays array_merge_recursive -- Merge two or more arrays recursively array_walk -- Apply a user function to every member of an array arsort -- Sort an array in reverse order and maintain index association asort -- Sort an array and maintain index association compact -- Create array containing variables and their values count -- Count elements in a variable current -- Return the current element in an array .
  18. Examples: Array count <?php $a[0]=1; $a[1]=2; $a[2]=5; $result= count($a); echo $result; ?>
  19. Combine array Creates an array by using one array for keys and another for its value Example: <?php $a=array("green","red", "yelllow"); $b=array("avocoda","apple" ,"banana"); $c=array_combine($a,$b); print_r($c); ?>
  20. Array Sort Sort an array (according to alphabet) Example: <?php $fruits=array("lemon","orange" ,"banana"); sort($fruits); foreach ($fruits as $keys =>$val) { Echo "fruits <br>[". $keys ."]=". $val .""; } ?>
  21. Strings in PHP
  22. Strings String is a series of character. Save as bytes. A string literal can be specified in three different ways:  single quoted  double quoted
  23. Single-quoted Strings In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash Example usage echo 'this is a simple string'; echo 'You can embed newlines in strings, just like this.'; echo ‘Douglas MacArthur said "I'll be back” when leaving the Phillipines'; echo 'Are you sure you want to delete C:*.*?';
  24. Double-quoted Strings In double-quoted strings,  variables are interpreted to their values, and  various characters can be escaped  n linefeed  r carriage return  t horizontal tab  backslash  $ dollar sign  ” double quote  [0-7]{1,3} a character in octal notation  x[0-9A-Fa-f]{1,2} a character in hexadecimal notation
  25. String-manipulation functions PHP provides huge range of string- manipulation functions:  addcslashes -- Quote string with slashes in a C style  addslashes -- Quote string with slashes  count_chars -- Return information about characters used in a string  echo -- Output one or more strings.  explode -- Split a string by string  implode -- Join array elements with a string  join -- Join array elements with a string  ltrim -- Strip whitespace from the beginning of a string  md5 -- Calculate the md5 hash of a string  strpos -- Find position of first occurrence of a string
  26.  stristr -- Case-insensitive strstr()  strrchr -- Find the last occurrence of a character in a string  str_repeat -- Repeat a string  strrev -- Reverse a string  strrpos -- Find position of last occurrence of a char in a string  strspn -- Find length of initial segment matching mask  strstr -- Find first occurrence of a string  strtolower -- Make a string lowercase  strtoupper -- Make a string uppercase  str_replace -- Replace all occurrences of the search string with the replacement string  strncmp -- Binary safe string comparison of the first n characters Some examples are given next:
  27. Examples: strlen: Get string also include space.It counts from 1. <?php $str="bebo technology"; $result=strlen ($str); echo "the string length is $result"; echo "<br>"; ?> Syntax: strlen(string);
  28. Examples Strpos This function return the position of particular character in string. It counts from 0. Example: <?php $numbered_string="1234567890"; $five_pos=strpos($numbered_string, "5"); echo "the position of 4 in our string is " . $five_pos; ?> Syntax: Strpos(string,”char position to be found”)
  29. Examples: explode function The explode function break a string Into array. <?php $array="welcome to btes"; print_r (explode (" ","$array")); ?> Syntax: explode (seprator,string);
  30. Examples: Implode function join array elements with a string. <?php $array=array('kunika', 'verma', ''); $comma_seprated=implode (", ", $array); echo $comma_seprated; ?> Syntax: implode (seprator,string);
  31. Include() and require() functions
  32. INCLUDE AND REQUIRE FUNCTIONS PHP include and require Statements In PHP, you can insert the content of one PHP file into another PHP file before the server executes it. The include and require statements are used to insert useful codes written in other files, in the flow of execution. Include and require are identical, except upon failure: Require will produce a fatal error (E_COMPILE_ERROR) and stop the script. Include will only produce a warning (E_WARNING) and the script will continue. Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.
  33. PHP include and require statement Syntax:- include 'filename'; or require 'filename'; Example: Assume that you have a standard header file, called "header.php". To include the header file in a page, use include/require: <html> <body> <?php include 'header.php'; ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html>
  34. Example 2: Assume we have a standard menu file that should be used on all pages. "menu.php": echo '<a href=“#">Home</a> <a href=“#">Tutorials</a> <a href=“#">About Us</a> <a href=“#">Contact Us</a>'; All pages in the Web site should include this menu file. <html> <body> <div class="leftmenu"> <?php include 'menu.php'; ?> </div> <h1>Welcome to my home page.</h1> <p>Some text.</p> </body> </html>
  35. PHP Looping
  36. While loop The while loop executes a block of code as long as the specified condition is true. Syntax: while (condition is true)   {   code to be executed;   } The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):
  37. Example: <?php $x=1; while($x<=5)   {   echo "The number is: $x <br>";   $x++;   } ?>
  38. Do-while loop The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax do   {   code to be executed;   } while (condition is true); The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
  39. Example: <?php $x=1; do   {   echo "The number is: $x <br>";   $x++;   } while ($x<=5) ?>
  40. for: The for loop is used when you know in advance how many times the script should run. Syntax: for (int counter; testcounter; increment counter)   {   code to be executed;   } Parameters: intcounter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value For loop
  41. foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax: foreach ($array as $value)   {   code to be executed;   } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
  42. Example: <?php $a=array(1,2,3,4,5); foreach ($a as $value) { ?> <div style="background-color:pink; width:50;"> <?php echo $value; ?> </div> </br> <?php } ?>
  43. MYSQL and PHP
  44. PHP is designed to work with the MySQL database. However, it can also connect to other database systems such as Oracle, Sybase, etc., using ODBC. Handles very large databases; very fast performance. Why are we using MySQL?  Free (much cheaper than Oracle!)  Each student can install MySQL locally.  Easy to use Shell for creating tables, querying tables, etc.  Easy to use with Java JDBC
  45. PHPMY ADMIN phpMyAdmin  is a free and open source tool written in PHP intended to handle the administration of Mysql with the use of a web browser. It can perform various tasks such as creating, modifying or deleting databases, tables, fields or rows; executing SQL statements; or managing users and permissions. Syntax: localhost/phpmyadmin
  46. How to connect with PHP? Use the My SQL connect routine  mysql_connect($host, $user, $password)  $user and $password will be your account details Mysql_connect will return a link ID  $link = mysql_connect($host, $user, $password)  if(!$link) { echo “Unable to connect”; } Always check the link to ensure that the database connection was successful
  47. Selecting a database Once a link has been established, select a database  mysql_select_db($dbname, [$link])  []optional – uses last created $link if not given mysql_select_db returns a Boolean indicating status $result = mysql_select_db(“students”) If(!$result) { echo “No database”; }
  48. How to create database in Mysql
  49. How to create tables in Mysql Click on your database name. Then create table option will show. It all show in fig:
  50. Data Types
  51. Change the attributes
  52. Mysql Queries
  53. Query types: Insert query Select query Delete query Update query Join query
  54. INSERT Query: INSERT INTO INSERT INTO [table]([fields,…] VALUES([newvalues,…]). [table] indicates which table to insert into. [fields] is a comma separated list of fields that are being used. [newvalues] is comma separated list of values that directly correspond to the [fields]. Syntax: “insert into managenews(fields) (values)”;
  55. Example:
  56. In database:
  57. Selection query: SELECT  SELECT [fields,…] FROM [table] WHERE [criteria] ORDER BY [field] [asc,desc] [fields] can be * for all or field names separated by commas [table] is the name of the table to use. Syntax: “select * from managenews(tablename)”:
  58. Example:
  59. Delete Query: DELETE  DELETE FROM [table] WHERE [criteria] Simple and dangerous statements [table] to delete from [criteria] specifying records to delete  No criteria deletes all records. Syntax: “delete from managenews(tablename)”;
  60. Update Query: UPDATE  UPDATE [table] SET [field=value,…] WHERE [criteria] [table] denotes the table to update [field=value,…] is a comma separated list of values for fields Syntax: “update managenews(table name) set (field=‘value’)”; Quick example: $query = “UPDATE managenews SET news='$news',date='$date‘ where id=".$id; $result = mysql_query($query); If(!$result) { echo “Update failed!”; } else { echo “Update successful!”; }
  61. Join Query: JOINs can be used to combine tables. A join can be classified in the from clause which list the two input relations. Types of joins: 1) Join 2) Inner join 3) Outer join 4) Left join 5) Right join
  62. Tables for join:
  63. How to Join: Consist full data which we Show in our Query. Syntax: select Persons.Firstname, Persons.Lastname, Orders.Orderno from Persons JOIN Orders ON Persons.P_Id=Orders.P_Id Output:
  64. Inner join: Simplest type of join Also called: Equality join, Equijoin, Natural join VALUES in one table equal to values in other table Syntax: select Persons.Firstname, Persons.Lastname, Orders.Orderno from Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id Syntax:
  65. Outer join Outer joins return  all rows from one table (called inner table) and  only matching rows from second table (outer table) Fields are different in outer join Syntax: select Persons.Firstname, Persons.Lastname, Orders.Orderno from Persons OUTER JOIN Orders ON Persons.P_Id=Orders.P_Id
  66. Left Join: Left join pick the left outer cell data. Syntax: select Persons.Firstname, Persons.Lastname, Orders.Orderno from Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id
  67. Important: Distinct: Count one for duplicate enteries. Syntax: Select distinct (category) from (tablename). Limits: limit the counting for display. Syntax: select * from products (tablename) limit 0,10 Order by: set by ascending or descending order Syntax: Select * from (tablename) order by (productname) ASC DESC Ob_start(); if we use 2 headers on same page. use before html. Ob_flush(); closing tag after html closing tag.
  68. 70 Accessing Query Result Information The mysql_num_rows() function returns the number of rows in a query result The mysql_num_fields() function returns the number of fields in a query result Both functions accept a database connection variable as an argument The mysql_query() function sends SQL statements to MySQL You use the mysql_create_db() function to create a new database The mysql_select_db() function selects a database You use the mysql_drop_db() function to delete a database mysql_fetch_array() for fetch array by rows.