PHP and MySQL

From Script | Spoken-Tutorial
Revision as of 18:42, 10 December 2012 by Minal (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

PHP or "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP. MySQL is a RDBMS(Relational database management system). We use such a system in order to store, retrieve and manage data related to our applications. Apache is an Open Source web server in wide usage. A web-server is required to host a web-application(webpage) on a remote server and is responsible for processing the request from the client, who wants to access the application(or webpage).

The tutorials on this page are derived from the videos available at http://phpacademy.org/. Our special thanks to Alex Garrett, founder of phpacademy.

The contributors who helped create the outline, transcribe, create the tutorials are - Ankit Bahuguna (Arya College of Engineering and I.T., Jaipur), Arvind Ravi, Madhur Sudarshan, Siddharth Kaliappan, Anoushka Banavar, Harini Alladi, Antara Atrey, Bhavini Pant, Joshua Mathew, Evan Varkey, Osama Butt, Juanita Jayakar, Royston Rodrigues, Deepika Rajput and Nancy Varkey. Support materails have been developed by Madhulika Goyal, Saurabh Gadgil, Muthu, Ankit Bahuguna and Nancy Varkey - all from IIT Bombay. The effort has been moderated and coordinated by the Spoken Tutorial team, IIT Bombay.
Special thanks to all our novice reviewers, too!

Please use this template to write the scripts SCRIPT TEMPLATE

PHP Basics: Level 1

Installing a Webserver with PHP and MySQL (XAMPP)
  1. XAMPP in Windows    
    • Installing XAMPP in Windows
    • XAMPP is a cumulative package consisting of Apache, PHP and MySQL Packages is available for Windows
    • In this tutorial the XAMPP will be installed and the default Webserver directory will be "htdocs".
  2. XAMPP in Linux    
    • Installing XAMPP in Linux
    • XAMPP is a cumulative package consisting of Apache, PHP and MySQL Packages is available for Linux
    • In this tutorial the XAMPP will be installed and the default Webserver directory will be "opt".

    Echo PHP Function, PHP Variables, If and Switch Statements
  3. Echo Function    
    • The echo() function outputs one or more strings.
    • Syntax: echo(strings);
    • Ex. echo "Hello World!";
  4. Variables in PHP    
    • Variables are used for storing values, like text strings, numbers or arrays.
    • When a variable is declared, it can be used over and over again in your script.
    • All variables in PHP start with a $ sign symbol.
    • The correct way of declaring a variable in PHP: $var_name = value;
  5. If Statement    
    • if statement - use this statement to execute some code only if a specified condition is true.
    • if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false.
    • if...elseif....else statement - use this statement to select one of several blocks of code to be executed.
  6. Switch Statement    
    • switch statement - use this statement to select one of many blocks of code to be executed

    PHP Operators
  7. Arithmatic Operators    
    • Ex. +,-,*,/,%,++,--
  8. Comparison Operators    
    • Ex. ==,!=,<>,>,<,>=,<=
  9. Logical Operators    
    • Ex. && (AND),|| (OR),! (NOT)

    Arrays in PHP
  10. Arrays    
    • An array stores multiple values in one single variable.
    • Numeric array - An array with a numeric index.
    • Associative array - An array where each ID key is associated with a value.
    • Ex. Numeric Array: $fruits=array("Apple","Mango","Banana","Grapes");
  11. Multi-Dimensional Arrays    
    • 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.

    Loops in PHP
    • Loops execute a block of code a specified number of times, or while a specified condition is true.
  12. Loops - While Statement    
    • The while loop executes a block of code while a condition is true.
      while (condition)
      {
      code to be executed;
      }
  13. Loops - Do-While Statement    
    • The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
      do
      {
      code to be executed;
      }while (condition);
  14. Loops - For Statement    
    • The for loop is used when you know in advance how many times the script should run.
    • Syntax:
      for (init; condition; increment)
      {
      code to be executed;
      }
  15. Loops - Foreach Statement    
    • The foreach loop is used to loop through arrays.
      foreach ($array as $value)
      {
      code to be executed;
      }

    Functions in PHP
  16. Functions (Basic)   
    • To keep the script from being executed when the page loads, you can put it into a function.
    • A function will be executed by a call to the function.
    • You may call a function from anywhere within a page.
    • Syntax:
      function functionName()
      {
      code to be executed;
      }
  17. Functions (Advanced)   
    • We can also pass parameters to functions during both the declaration and calling time.
    • function functionName($param1,$param2); //during function call.
    • function functionName($param1,$param2)
      {
      code to be executed
      }

    PHP Special Variables
  18. GET Variable    
    • The built-in $_GET function is used to collect values from a form sent with method="get".
    • Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar)
    • It has limits on the amount of information to send.
  19. POST Variable    
    • The built-in $_POST function is used to collect values from a form sent with method="post".
    • Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

    PHP and HTML
  20. Embedding PHP    
    • We can embed our PHP code anywhere in the webpage, by enclosing our script within the <?php...... //SCRIPT.......?>
  21. Common Way to Display HTML    
    • We can also use the HTML Code within the PHP Script. Almost each of the HTML Tags can be used within a PHP Script.
    Common Errors
    • The PHP Engine in the webserver also displays the user the error in case there is something wrong in the code along with the tentative line number where the fault may have occurred. Thus, in this way we can eradicate errors.
  22. Common Errors (Part 1)   
    • Learn how to spot errors and how to fix them
    • Common Parse errors
    • Parse errors due to missing comma or semicolon
    • Parse errors due to not ending single or double quotes correctly
  23. Common Errors (Part 2)   
    • Parse error due to missing or extra brackets
    • Matching brackets during complex mathematical operations
    • Purpose and usefulness of correct indentation
    • Errors due to missing or extra characters
    • Undefined variable and undefined index errors
  24. Common Errors (Part 3)   
    • "Cannot modify header information - headers already sent by..." errors when using header() function
    • Using ob_start() to turn on output buffering
    • "Failed to open stream; no such file or directory in..." errors when including a invalid file
    • Using a @ symbol to suppress errors

MYSQL Tutorials: Level 2

MySQL is a Relational Database Management System (RDBMS) that runs as a server providing multiuser access to a number of databases. A third party open source software "phpMyAdmin" will be used as a web-based front end for managing MySQL databases easily and efficiently. It is widely installed by Web hosts worldwide, since it is developed in PHP and is included in the convenient LAMP stack, MAMP, and WAMP software bundle installers.

  1. MySQL (Part 1)   
    • An Introduction to the PHPMyAdmin Interface.
    • Creating a New Database
    • Creating a new Table and entering the value of the field with the requisite datatype.
    • SQL Query displayed in the PHPMyAdmin window.
  2. MySQL (Part 2)   
    • Connecting to the database and inserting dummy data into the database.
    • mysql_connect("server_addr", "username", "password") - Connect to the Database Server with the authorised user and password.
    • mysql_select_db("database_name") - Selecting a database within a connected database server.
  3. MySQL (Part 3)   
    • Writing some data into the database (INSERT and UPDATE Queries).
    • mysql_query('TYPE_HERE_YOUR_MYSQL_QUERY') - This function is used to run specific queries on our database.
    • INSERT QUERY - INSERT into table values ('att1', 'att2' , 'att3', 'att4' ,'att5') //Inserts Data into the table
    • UPDATE QUERY - UPDATE table_name SET att1='xyz' //Updates the Existing values stored in the table of the database.
  4. MySQL (Part 4)   
    • Getting data from the database table and displaying it.
    • SELECT QUERY - SELECT * FROM table_name WHERE att1='abc' // Query returns the value from the database where att1 = abc
    • mysql_num_rows() - Gives us the number of rows there are in the query we have just given out.
    • ORDER BY - Helps to order the output result as when selecting the values form the database. {Use of DESC for Descending ordering / ASC for Ascending ordering}
  5. MySQL (Part 5)   
    • mysql_fetch_assoc — Fetch a result row as an associative array.
    • array mysql_fetch_assoc ( resource $result ) //Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
  6. MySQL (Part 6)   
    • Getting data from the database with the help of an HTML form.
    • Creating a FORM where a user can specify a name and selecting the appropriate value from the database.
  7. MySQL (Part 7)   
    • Changing the existing values of the databse table using HTML Forms.
    • Update unique records using the id than individual values.
  8. MySQL (Part 8)   
    • DELETE QUERY - To Delete the specific or all the entries of the Database.
    • DELETE FROM table_name WHERE field='xyz' // Deletes the entry from the database where the field = xyz.

PHP Advanced: Level 3

  1. Name Splitter(Part 1)   
    • We Input a fullname into a form and then splitting it into firstname and lastname
    • Use of : strlen(string) - This function counts total no of characters, including numbers and white spaces in the string
    • Use of: mb_substr(string,starting_position,no_of_characters) - This function takes a specific character from a string and a range of no of characters preceeding it.
  2. Name Splitter(Part 2)   
    • Divided the string into 2 halves through searching space, first half is stored as firstname and second half as lastname.
    • Use of : substn(string,starting_position,length) - This function results a substring starting from specified position to no of characters required.
  3. PHP Dynamic Pages (Part 1)   
    • We learn to create website with standard template and when on clicking the link changes only the content of page ,new page is not loaded.
    • Use of : include(variable) - This function is used to brought up all the content of variable page onto the current page.So that by changing the variable content of the website can be altered without reloading a similar page content everytime.
  4. PHP Dynamic Pages (Part 2)   
    • Making the dynamic linking user-friendly in case an error is obtained by include() function, i.e. checking if the file connected exists or not.
    • Use of : file_exists(variable) ->This function is results boolean value true(1) if the file exists and false(0) if not.
  5. Simple Visitor Counter    
    • Counts how many users have viewed your page as per count of refresh button clicked
    • fopen("file_name","parameter") opens a file (Creates it if not exists).parameter assigns the mode, w for writting mode, a for append mode
    • file_get_contents("file_name")- This function is used to obtain content from the file.
    • fwrite("file_name",variable) - This function writes into the file value present in variable.
  6. Unique Visitor Counter (Part 1)   
    • Counts how many users visiting based on their IP addresses. It obtains IP addresses stored in ip-file to match with user's IP
    • count() - This function is used to count no of lines in the file.
    • $_SERVER[] - This is an array containing information such as headers, paths and script locations.
    • $_SERVER['REMOTE_ADDR'] - It informs about the IP address from which the user is viewing the current page.
  7. Unique Visitor Counter (Part 2)   
    • Retrieves IP addresses stored and compares them with IP of user viewing the current page.
    • fopen("file_name","parameter") opens a file (Creates it if not exists).parameter assigns the mode, w for writing mode, a for append mode
    • fwrite("file_name",variable) - This function writes into the file value present in variable.
    • intval(string) -This function converts an string value into a integer value.
  8. Unique Visitor Counter (Part 3)   
    • In this video errors have been corrected. Here counter keeps on increases
  9. PHP String Functions (Part 1)   
    • strlen(string) - This function counts total no of characters, including numbers and white spaces in the string
    • mb_substr(string,starting_position,no_of_characters) - This function takes a specific character from a string and a range of no of characters preceeding it.
    • explode("delimiter",string) -This function breaks down the string into a array. Delimiter is used to know from where to break string.
    • implode(string,"delimiter") -This function joins the array into a string. Delimiter is used to know how to join array elements.
    • nl2br() -This function prints the content in exactly same form as written. Used in case for breaking lines.
  10. PHP String Functions (Part 2)   
    • strrev(string) -This function is used to reverse the inputed string
    • strtolower(string) -This function is used to convert all alphabatic characters in string to thier small/lower case form.
    • strtoupper(string) -This function is used to convert all alphabatic characters in string to thier capital/upper case form.
    • substr_count(string,sub_string,) -This counts the no of substrings matching the particular value in string. It retuns an integer value.
    • substr_replace(original_string,string_to_replace) -This function replaces the cuntent of substring into original string.
  11. Basic PHP Proxy    
    • Providing the proxy to our page of a url.
    • foreach() - this loop looks through a block of code for each element in an array.
    • erag_replace(current_content, altered content,page) - This function is used to manipulate content of a proxy page.
  12. Basic Advert Rotation (Part 1)   
  13. Basic Advert Rotation (Part 2)   
  14. Find and Replace    
  15. Date and Time (Part 1)    
  16. Date and Time (Part 2)    
  17. Creating Images with PHP    
  18. File Upload (Part 1)    
    • Setup html form for file uploading
    • Upload file and get file related information like file name, file size, etc
    • Check for error messages after uploading file
  19. File Upload (Part 2)    
    • Move file from temporary area to user specified location
    • Restrict uploading to only specific file type
    • Restrict uploading to a maximum file size
  20. Cookies (Part 1)   
    • What are cookies
    • Set cookies using setcookie function
    • Understaing how to set expiry time of cookies
    • Read and print values from existing cookies
    • Print every cookie that we have stored
  21. Cookies (Part 2)   
    • Check if a cookie exists or not using isset
    • Unset a cookie when no longer required
    • Change the value of a existing cookie
  22. Sessions    
    • A PHP session variable is used to store information about, or change settings for a user session.
    • Session variables hold information about one single user, and are available to all pages in one application.
    • session_start() - Starting a PHP Session
    • $_SESSION['variable_name']=value - Stores the value in the Session variable.
    • session_stop() - Stopping a PHP Session
  23. Search Engine Crawler Detection    
  24. Swear Word Filter (Part 1)   
  25. Swear Word Filter (Part 2)   
  26. Rename Function    
  27. SQL Injection (Part 1)   
  28. SQL Injection (Part 2)   
  29. MD5 Encryption    
    • Calculates the MD5 hash of str using the RSA Data Security, Inc.'s MD5 Message-Digest Algorithm, and returns that hash (Its a one way encrypting technique).
    • Syntax  : string md5 ( string $str [, bool $raw_output = false ] )
    • Used in encrypting passwords and storing them in a database.
  30. Sending Email (Part 1)   
    • Create HTML form for getting email subject and message from the user
    • Using the mail() function to send email
  31. Sending Email (Part 2)   
    • Validating whether the name and message have been entered by the user
    • Check the length of the string using the strlen() function.
    • Set up the to, subject and message field of the mail() function
    • Send email and check for any errors
  32. Sending Email (Part 3)   
    • Fix the "Sendmail from not set in php dot ini" error
    • Create the mail "From:" header
    • Using a local or external mail server to send email
    • Using the ini_set() and ini_get() functions to set and read internal php configuration options respectively
  33. Upload an Avatar Profile Image (Part 1)   
  34. Upload an Avatar Profile Image (Part 2)   
  35. Upload an Avatar Profile Image (Part 3)   
  36. Upload an Avatar Profile Image (Part 4)   
  37. Form Validation(Part 1)   
  38. Form Validation(Part 2)   
  39. Admin Only Pages (Part 1)   
  40. Admin Only Pages (Part 2)   
  41. Admin Only Pages (Part 3)   
  42. Create a news Feature (Part 1)   
  43. Create a news Feature (Part 2)   
  44. Create a news Feature (Part 3)   
  45. Display Images from a Directory    
    • Using opendir() to open a directory handle
    • Using readdir() to read a directory that is already opened
    • Printing the directory listing
  46. Pagination (Part 1)   
  47. Pagination (Part 2)   
  48. Language Chooser    
  49. PHP/ MYSQL Based Project - Basic Register and Login Module
    1. User Login
      1. User Login Part 1    
        • Collecting information from user in a form & connecting to authorized database.
        • mysql_connect("hostname", "username", "password") - Connect to the Database Server with the authorized user and password.
        • mysql_select_db("database_name") - This selects a database within a connected database server
      2. User Login Part 2    
        • retrieves information about inputed username and checks whether given password matches with the password in database.
        • mysql_query('TYPE_HERE_YOUR_MYSQL_QUERY') - It is used to run specific queries on our database.Here it collects information from field username from specified table.
        • mysql_num_rows('query') - This function is user to counts no of rows retrieved from the query given to the database.
        • mysql_fetch_assoc('query')- This function fetches required information from the database in the form of array.
      3. User Login Part 3    
        • Creating session for holding value and destroying that value by destroying session.
        • start_session() - Starts session to hold information from one pages to other until the session exists.
        • $_SESSION['variable_name']=value - Stores the value in the session variable.
        • session_destroy() - destroys the value present in session variable.
    2. User Password Change
      1. User Password Change Part 1    
        • We learn to obtain old existing password and new password from the user.
        • start_session() - Hold information from previous pages to session page.
        • $variable_name=$_SESSION['value'] - to retrieve value containing in PHP variable.
      2. User Password Change Part 2    
        • Checking whether encrypted old password matches with the database password and new password is same as confirm password.
        • md5("parameter")- encrypts parameter into irreversible logical code.
        • mysql_connect("hostname", "username", "password") - Connect to the Database Server with the authorized user and password.
        • mysql_select_db("database_name") - This selects a database within a connected database server
        • mysql_query('TYPE_HERE_YOUR_MYSQL_QUERY') - It is used to run specific queries on our database.Here it retrieves password of user logged in.
      3. User Password Change Part 3    
        • updating the new password in database.
        • mysql_query('TYPE_HERE_YOUR_MYSQL_QUERY') - It is used to run specific queries on our database. Here it updates new password into database.
    3. User Registration
      1. User Registration Part 1    
        • Creating a form which allows user to input values in page
      2. User Registration Part 2    
        • Striping tags of inputed strings and converting password into md5 encryption.
        • Use of : strip_tags(strigs) - cuts down unnecessary spaces,html tags and queries from string.
      3. User Registration Part 3    
        • Checking whether the username and password provided meet the required length sizes.
        • Use of : strlen("string") - counts th character length of the string.
      4. User Registration Part 4    
        • Inserting inputed information from the user into the database table through query.
        • mysql_connect("hostname", "username", "password") - Connect to the Database Server with the authorized user and password.
        • mysql_select_db("database_name") - This selects a database within a connected database server
        • mysql_query('TYPE_HERE_YOUR_MYSQL_QUERY') - It is used to run specific queries on our database. Here it inserts different fields into the database table.
      5. User Registration Part 5    
        • Converting the password inputed from user to md5 encrypt form.
        • md5("parameter")- encrypts parameter into irreversible logical code.
      6. User Registration Part 6    
        • Checking the username provided so that condition for duplicate username can be avoided.
        • mysql_query('TYPE_HERE_YOUR_MYSQL_QUERY') - This is used to run specific queries on our database. Here it checks if username already exists in database.
        • mysql_num_rows('query') - This function is used to counts no of rows retieved from the query.
        • strtolower(string) - converts all characters of string into lower case.

Contributors and Content Editors

Minal, PoojaMoolya