Wednesday, 27 March 2013

Multiple Select Dropdown List with PHP Ajax


Multiple Select Dropdown List with AJAX

This tutorial presents an AJAX script that can be used to create dynamically multiple Select lists with data from a MySQL table.

First, a single select list is displayed on the page, then when the user chooses an option, it calls an Ajax function that acceses a PHP file that will return a select list according to the option selected. The Ajax function receives and displays the second select list.
When the users selects an option from the second select list, this script can display a third list of options, according to the options selected in the first an second select lists.

The script contains two files, a PHP file (named "select_list.php") with the code that selects data from a MySQL table and returns a select drop down list, and a JS file (named "ajax_select.js") with the Ajax code that accesses the PHP file.
You can copy and use the code for these files displayed below, or download the files from: Script Multiple Select Dropdown List

The code for select_list.php

<?php
// Multiple select lists - http://coursesweb.net/ajax/
if(!isset($_SESSION)) session_start();

// Here add your own data for connecting to MySQL database
$server = 'localhost';
$user = 'username';
$pass = 'password';
$dbase = 'dbname';

// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'col_description' if you don`t want to display their data too
$table = 'table_name';
$ar_cols = array('col_select1', 'col_select2', 'col_select3', 'col_description');

$preid = 'slo_'; // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0]; // the variable used for the column that wil be selected
$re_html = ''; // will store the returned html code

// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
// set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
$col = trim(strip_tags($_POST['col']));
$wval = "'".trim(strip_tags($_POST['wval']))."'";
}

$key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1]; // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE

// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';

$conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database

if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); } // check connection

// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
$ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]];
}

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where;

$result = $conn->query($sql); // perform the query and store the result

// if the $result contains at least one row
if ($result->num_rows > 0) {
// sets the "onchange" event, which is added in <select> tag
$onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';

// sets the select tag list (and the first <option>), if it's not the last column
if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';

while($row = $result->fetch_assoc()) {
// if its the last column, reurns its data, else, adds data in OPTION tags
if($col==$ar_cols[$last_key]) $re_html .= '<br/>'. $row[$col];
else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>';
}

if($col!=$ar_cols[$last_key]) $re_html .= '</select> '; // ends the Select list
}
else { $re_html = '0 results'; }

$conn->close();

// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
// adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
// with ID in each SPAN, according to the columns added in $ar_cols
for($i=1; $i<count($ar_cols); $i++) {
if($ar_cols[$i]===null) continue;
if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>';
}

// adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
$re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}
else echo $re_html;
?>

The code for ajax_select.js

// Multiple select lists - http://coursesweb.net/ajax/

// function used to remove the next lists already displayed when it chooses other options
function removeLists(colid) {
var z = 0;
// removes data in elements with the id stored in the "ar_cols" variable
// starting with the element with the id value passed in colid
for(var i=1; i<ar_cols.length; i++) {
if(ar_cols[i]==null) continue;
if(ar_cols[i]==colid) z = 1;
if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
}
}

// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;

if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } // for Forefox, IE7+, Opera, Safari
else if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } // IE5 or 6

return xmlHttp;
}

// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) {
removeLists(col); // removes the already next selects displayed

// if the value of wval is not '- - -' and '' (the first option)
if(wval!='- - -' && wval!='') {
var request = get_XmlHttp(); // call the function with the XMLHttpRequest instance
var php_file = 'select_list.php'; // path and name of the php file

// create pairs index=value with data that must be sent to server
var data_send = 'col='+col+'&wval='+wval;

request.open("POST", php_file, true); // set the request

document.getElementById(preid+col).innerHTML = 'Loadding...'; // display a loading notification

// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send); // calls the send() method with data_send

// Check request status
// If the response is received completely, will be added into the tag with id value of "col"
request.onreadystatechange = function() {
if (request.readyState==4) {
document.getElementById(preid+col).innerHTML = request.responseText;
}
}
}
}

Usage Script Multiple Select Drop down List

1) Create the files: "select_list.php" and "ajax_select.js" on your server (with the code presented above), in the same directory.
In the PHP script, add your own data for connecting to MySQL, the table name (in $table) and the name of the columns with data for each Select list (in the array $ar_cols).

- For example, if you have a table named "cities", and you want to create a triple select drop down list with data stored in the columns: "state", "city", and "villages"; then to display some descriptions about each village stored in another column named "villdata", change the value of the $table and $ar_cols variables like this:
// Here add the name of the table and columns that will be used for select lists, in their order
$table = 'cities';
$ar_cols = array('state', 'city', 'villages', 'villdata');
If you want to display only the three select lists (state, city, villages), or you not have a column with description, add null for the last element (in place of 'villdata').

- If you want to create two select drop down list, and then a description for the options of the second Select, add like this:
// Here add the name of the table and columns that will be used for select lists, in their order
$table = 'table_name';
$ar_cols = array('col_select1', 'col_select2', 'col_description');
If you want to display only the Select lists associated with "col_select1" and "col_select2", replace 'col_description' with null.

2) In the web page in which you want to display the select lists with Ajax:
- You must include the "select_list.php" file at the beginning of the page, by adding the following php code, before the HTML code, or any output data (this because it uses session_start()):
<?php include 'select_list.php'; ?>

- Include the "ajax_select.js" file in the HEAD section of the HTML code, by adding the following code:
<script src="ajax_select.js" type="text/javascript"></script>

- Then, in the form where you want to display the Select lists, add:
Select: <?php echo $re_html; ?>
Like you can see in the example below, or in the "test.php" file (in the archive downloaded from the link above).

• The PHP script creates the first <select> with the options from the first column added in $ar_cols Array, then creates HTML tags in which Ajax will add the next Select lists. These HTML tags has an unique ID composed by the string added in $preid variable and the name of the column. The $preid is used to be sure that there isn't another element with the same ID on the page.

If you want to include the select drop down lists into a form, and then to send and use the selected options in other PHP script, you can get the selected value using the "name" of each select, which is the same with the column name with the options for that select, added in the $ar_cols variable.
- For example, the first <select> has name="col_select1" (the first value added in the $ar_cols array). To get the selected option of this dropdown list, use in your PHP script: $_POST['col_select1'].
The second Select list has name="col_select2" (the second value added in the $ar_cols array), and so on.

If you modify something in the instrutions of the PHP script or in the JavaScript functions, without knowing what you do, it's pretty sure the script to not work.

Example Triple Select drop down list

Here's is a concrete example. We have in MySQL a table named "sites" with these columns: id, site, menu, categ, links; having the following records:
idsitemenucateglinks
1MarPlo.netCoursesAjaxwww.marplo.net/ajax/obiectul_xmlhttprequest.html
2MarPlo.netCoursesAjaxwww.marplo.net/ajax/ajax_get_php.html
3MarPlo.netCoursesAjaxwww.marplo.net/ajax/tutoriale_ajax_json.html
4MarPlo.netCoursesJavaScriptwww.marplo.net/javascript/sintaxajs.html
5MarPlo.netCoursesJavaScriptwww.marplo.net/javascript/notiuni_de_baza.html
6MarPlo.netCoursesJavaScriptwww.marplo.net/javascript/getelementbyid.html
7MarPlo.netCoursesEnglishwww.marplo.net/engleza/gramatica
8MarPlo.netCoursesEnglishwww.marplo.net/engleza/exercitii
9MarPlo.netCoursesEnglishwww.marplo.net/engleza/download_carti-programe-audio
10MarPlo.netAnimeSlice of lifewww.marplo.net/anime/h2o_footprints_sand-a
11MarPlo.netAnimeSlice of lifewww.marplo.net/anime/chobits-a
12MarPlo.netAnimeSlice of lifewww.marplo.net/anime/hayate_no_gotoku-a
13MarPlo.netAnimeComedywww.marplo.net/anime/angel_tales-a
14MarPlo.netAnimeComedywww.marplo.net/anime/my_bride_is_a_mermaid-a
15MarPlo.netAnimeComedywww.marplo.net/anime/nodame_cantabile-a
16MarPlo.netAnimeRomanticwww.marplo.net/anime/clannad-a
17MarPlo.netAnimeRomanticwww.marplo.net/anime/bokura_ga_ita-a
18MarPlo.netAnimeRomanticwww.marplo.net/anime/peach_girl-a
19MarPlo.netGamesAdventure-Mysterywww.marplo.net/jocuri/misson_to_mars-j
20MarPlo.netGamesAdventure-Mysterywww.marplo.net/jocuri/prince_of_persia-j
21MarPlo.netGamesAdventure-Mysterywww.marplo.net/jocuri/river_rapid_rampage-j
22MarPlo.netGamesLogic and Intuitionwww.marplo.net/jocuri/bloxorz-j
23MarPlo.netGamesLogic and Intuitionwww.marplo.net/jocuri/flash_chess_3-j
24MarPlo.netGamesLogic and Intuitionwww.marplo.net/jocuri/red_remover-j
25http://coursesweb.netPHP-MySQLLessonshttp://coursesweb.net/php-mysql/writing-php-scripts
26http://coursesweb.netPHP-MySQLLessonshttp://coursesweb.net/php-mysql/arrays
27http://coursesweb.netPHP-MySQLLessonshttp://coursesweb.net/php-mysql/php-mysql-using-mysqli
28http://coursesweb.netPHP-MySQLTutorialshttp://coursesweb.net/php-mysql/file_put_contents-file_get_contents-readfile-file_t
29http://coursesweb.netPHP-MySQLTutorialshttp://coursesweb.net/php-mysql/uploading-multiple-files_t
30CoursesWeb.netPHP-MySQLTutorialshttp://coursesweb.net/php-mysql/count-number-downloads-accesses_t
31http://coursesweb.netJavaScriptLessonshttp://coursesweb.net/javascript/variables-operators
32CoursesWeb.netJavaScriptLessonshttp://coursesweb.net/javascript/document-object-dom
33CoursesWeb.netJavaScriptLessonshttp://coursesweb.net/javascript/javascript-code-php
34CoursesWeb.netJavaScriptTutorialshttp://coursesweb.net/javascript/align-make-same-height_t
35CoursesWeb.netJavaScriptTutorialshttp://coursesweb.net/javascript/check-file-type-before-upload_t
36CoursesWeb.netJavaScriptTutorialshttp://coursesweb.net/javascript/display-simulate-loading-progress-bar_t
37CoursesWeb.netJavaScriptjQueryhttp://coursesweb.net/jquery/jquery-basics
38CoursesWeb.netJavaScriptjQueryhttp://coursesweb.net/jquery/animating-css-properties
39CoursesWeb.netJavaScriptjQueryhttp://coursesweb.net/jquery/drag-drop
40CoursesWeb.netFlash-AS3Flash Lessonshttp://coursesweb.net/flash/simple-flash-animation-save-export
41CoursesWeb.netFlash-AS3Flash Lessonshttp://coursesweb.net/flash/deco-tool
42CoursesWeb.netFlash-AS3Flash Lessonshttp://coursesweb.net/flash/motion-tween-flash-animation
43CoursesWeb.netFlash-AS3ActionScript Lessonshttp://coursesweb.net/actionscript/introduction-actionscript-3
44CoursesWeb.netFlash-AS3ActionScript Lessonshttp://coursesweb.net/actionscript/simple-script-actionscript
45CoursesWeb.netFlash-AS3ActionScript Lessonshttp://coursesweb.net/actionscript/oop-object-oriented-programming
46CoursesWeb.netFlash-AS3Tutorialshttp://coursesweb.net/flash/xml-actionscript-php-script_t
47CoursesWeb.netFlash-AS3Tutorialshttp://coursesweb.net/flash/access-objects-different-timeline_t
48CoursesWeb.netFlash-AS3Tutorialshttp://coursesweb.net/flash/actionscript-change-movieclip-color_t

We create a triple select list with options stored in the columns: "site", "menu", and "categ", then we'll display the data stored in the column "links", associated with the option selected in the last list (categ).
In the "select_list.php" we set the code:
// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'links' if you don't want to display their data too
$table = 'sites';
$ar_cols = array('site', 'menu', 'categ', 'links');

The web page that will display the Select lists has the following code:
<?php include 'select_list.php'; ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Triple Select drop down list with Ajax</title>
<script src="ajax_select.js" type="text/javascript"></script>
</head>
<body>

<form action="" method="post">
Select: <?php echo $re_html; ?>
</form>

</body>
</html>

- Here's the result:
Select sites: 

Example Double Select Drop down list

Now we create only two select dropdown list, with the options stored in the columns "site", and "menu" (in the same table presented above).
We just need to modify the $ar_cols variable (in "select_list.php"), by adding the elements 'site', 'menu', and null :
// Here add the name of the table and columns that will be used for select lists, in their order
$table = 'sites';
$ar_cols = array('site', 'menu', null);

- In the same web page created in the previous example, will result:
Select sites: 

Java Script Online Training Course Index


JavaScript Course - Free Lessons

Welcome to this JavaScript course.
JavaScript is ubiquitous on the World Wide Web. You can use JavaScript to make your Web pages more interactive, so that they react to a viewer's actions, and to give your Web pages some special visual effects.
JavaScript allows you to add additional features that a static HTML page can't provide without some script code.
The JavaScript lessons of this course are free and a good start for beginners, they offer the necessary elements to learn the JavaScript programming language and working with JS code.

JavaScript Lessons

  1. Introduction to JavaScript
    - A brief introduction about JavaScript, a programming language used to create interactive webpages and web aplications.
  2. JavaScript Syntax
    - About JavaScript code and syntax. How to write and use a simple JS code in the HTML page and external file.
  3. Variables and Operators
    - Understading and using variables and operators, the basics of programming.
  4. JavaScript Operators
    - JavaScript Operators, arithmetics, logicals, for strings, for functions, conditional operator, operators precedence.
  5. Conditional statements if, else, switch
    - This chapter begins by introducing you to conditional statements: if, else and switch. You will discover what they are and why they are useful to you in scripts.
  6. For loops
    - The FOR loops: for ... in and for each ... in. Block of code that allows you to repeat a section of code a certain number of times.
  7. While loops
    - Using while loops and Do While in JavaScript.
  8. Alert, Confirm and Prompt
    - How to use Alert, Prompt and Confirm, JS predefined windows.
  9. Functions
    - Using functions, declaring and calling functions with or without parameters.
  10. Functions - scope, arguments and recursive
    - Different ways to declare a function. About variable scope, arguments, nested and recursive functions.
  11. JavaScript Strings
    - String object, creating and using strings in JavaScript. Properties and methods of the string object.
  12. JavaScript Arrays
    - Array object, creating and using Arrays. Properties and methods of the array object. Moving through Array's elements.
  13. Associative Arrays
    - Creating and using Associative Arrays in JS, traversing and accesing elements of the associative array.
  14. The Number and Math Objects
    - About the Number object. Perform various calculations and complex operations with the Math object. Properties and methods of the Number and Math objects.
  15. Date Object
    - JS Date object, set and get certain time values that you can use in your scripts. Properties and methods of the Date object.
  16. Global Object
    - About Global object. Properties and methods (functions) of the Global object and a sample script example.
  17. JSON syntax in JavaScript
    - Learn how to use JSON syntax, to create array and objects using JSON format.
  18. Convert JSON in JavaScript
    - Convert strings with data in JSON format to a JavaScript object, convert JS objects to JSON string.
  19. Window Object
    - An Introduction to the Window Object. Properties and methods of the Window object and some examples.
  20. Document Object - DOM
    - DOM, Document Object Model, accessing and using the DOM with JavaScript. Document object properties and methods.
  21. Document object and Forms
    - Document Object and Forms. How to access and change the data from input form fields using DOM hierarchy.
  22. navigator and history objects
    - Level one JS browser objects: navigator, history. Properties, methods and examples.
  23. location and screen objects
    - JavaScript course - Other JS browser objects: location, screen. Properties, methods and examples.
  24. anchor and link object
    - JS HTML DOM objects, anchor and link; represent an HTML hyperlin tag. Properties, methods and examples.
  25. Form, text, textarea, file objects
    - Properties, methods and events of the form object and some of its sub-objects: text, password, hidden, textarea and file.
  26. Buttons, Checkbox, Radio, Select, Option objects
    - Otfer form sub-objects: Buttons, Checkbox, Radio, Select, Option. Properties, methods and events of these JS objects.
  27. JavaScript Events
    - Adding events in the HTML page. Examples and a list with JS Events for window, mouse, form elements and keyboard.
  28. Register event handlers and Detect events
    - How to Register event handlers and Detect events in JS, addEventListener method.
  29. Image object
    - JS Image object. Creating simple image effects using properties and methods of the Image object, preloading images.
  30. Frame / IFrame object
    - Properties of the Frame and IFrame object. Accesing frame elements, frame navigation.
  31. Cookies
    - Using Cookies, creating, reading and deleting cookies. Working in JavaScript with data from cookie.
  32. Working with getElementById
    - Working with getElementById. How to use the getElementById DOM method to get and set data in the HTML document.
  33. Working with getElementsByTagName
    - Working with getElementsByTagName. How to use the getElementsByTagName JS DOM method with HTML tags..
  34. querySelector and querySelectorAll
    - querySelector() and querySelectorAll(), two JavaScript functions very useful when working with HTML elements in JS.
  35. createElement and insertBefore
    - Using createElement and insertBefore JavaScript methods to Create and to add HTML elements in the web page.
  36. JavaScript code and PHP
    - Learn how to combine JavaScript code with PHP, to create JS scripts that use server side data.
  37. Creating and using classes in JavaScript
    - This lesson shows how to create, and use classes in JavaScript, with own properties and methods.

CSS Online Training Course Index


CSS Course - Free Lessons

This course teaches you the basics of Cascading Style Sheets, or CSS as it's commonly abbreviated.
CSS is a simple standardized syntax that gives web designers extensive control over the presentation of their web pages and is an essential component of web design today.
All you need is a simple text editor such as Notepad and a web browser, e.g. Mozilla Firefox, which is free.

CSS Lessons

  1. Writing CSS code
    - Writing CSS code, Cascading Style Sheets. Learn about CSS rules, Selectors, Properties and Values.
  2. Creating style sheets
    - Creating style sheets in the HTML document and external css file, import style sheets, adds comments.
  3. Configuring Fonts
    - Configuring Fonts, setting font type, size and font style, setting multiple values in a property.
  4. Configuring Text
    - Configuring text, setting text properties, line and word spacing, letter spacing, text decoration, align, white space, shadow.
  5. Backgrounds
    - Setting Backgrounds to HTML elements, background image, background properties: color, position.
  6. CSS Box Model
    - CSS course - Box Model, content-box properties: margin, width, height, padding, Min and Max dimensions, overflow.
  7. CSS Border
    - Draw different line styles around elements with CSS border properties, sets border-color, border-style, border-width. Shorten the stylesheet code with border shorthand.
  8. CSS Outline
    - Make the HTML element "stand out" with CSS outline properties, sets outline-color, outline-style, outline-width, outline shorthand.
  9. Display and Visibility
    - Learn how to Display a HTML element: inline, block, or to hide its Visibility in the web page.
  10. Positioning
    - Use the CSS position property to set the position of HTML elements in the web page, fixed, absolute, relative, z-index.
  11. CSS Float and Clear
    - How to use the CSS float property to push the elements horizontally to the left or right. Use "clear" to stop the wrapping effect of the float.
  12. Pseudo-classes
    - How to use pseudo-classes to add special effects to some elements of the same selector or class. Various examples with pseudo-classes applied to selectors, classes and form fields.
  13. CSS Pseudo-elements
    - Pseudo-elements (after, before, first-letter, first-line) to style certain aspects or parts of an element without introducing new markup or tags in the HTML document.
  14. Cursor property - Custom Cursors
    - How to control and create Custom Cursors with CSS, use images for cursor appearance.

HTML Online Training Course Index


HTML Course - Free Lessons

The knowledge of HTML is the most important step for those who want to build quality web pages.
- Here you will find tutorials, online lessons, examples, courses and resources that teach you HTML.
The HTML lessons in this course are free and are best suited for beginners in web development, who want tolearn how to create Web pages manually, using the HTML language.

HTML Lessons

  1. Introduction
    - A brief introduction about HTML (Hyper Text Markup Language), a language used to create webpages. Some introductive presentations.
  2. Basic HTML elements
    - The main HTML elements, HEAD, TITLE, BODY, the general structure of a HTML document.
  3. Building and editing HTML webpage
    - A lesson about how to build and edit a HTML webpage, using just a simple text editor.
  4. HTML Headings and Comments
    - What HTML Headings are, how to add headings, h1, h2, ... h6, and comments into an HTML document.
  5. Paragraphs, Line break, Horizontal rule
    - HTML course, create Paragraphs, add Line break and Horizontal rule.
  6. HTML Text Formatting
    - Text Formatting - how to use FONT tag, its attributes: size, color; and other formatting tags to display text in various format: bold, italic, underline, strike, ... etc.
  7. HTML Lists (UL, OL, LI, DL)
    - How to create unordered, ordered, and definition lists in a web page, <ul>, <ol>, <li>, <dl> tags.
  8. Adding images
    - Adding images in a web page, attributes of the IMG tag, src, width, height, and others.
  9. Hyperlinks - Links
    - Adding Hyperlinks in HTML document, create Links in a Web page, <a> tag.
  10. Image Map
    - Image Maps in HTML document, creating multiple areas and links in a single image-map. <map> and <area> tags.
  11. HTML Tables
    - Working with Tables. Table elements and structure, rows, cols, thead, tbody, caption, and attributes (width, height, border, align, colspan, rowspan, ...).
  12. Forms and Input
    - How to create Forms, input fields, buttons, select list, checkboxes, textarea, and other form elements.
  13. New Form elements and attributes in HTML5
    - New Form input types and attributes added in HTML5, date-pickers, number, range, email, url, search, color, datalist and other new elements.
  14. CSS - Cascading Style Sheets in HTML
    - Applying formatting using CSS - Cascading Style Sheets. Creating style rules in internal and external style sheet.
  15. DIV and SPAN
    - About DIV and SPAN HTML tags. How to use and work with DIV, SPAN and CSS styles.
  16. Using Frames
    - Working with frames in HTML, using FRAME, FRAMESET and IFRAME.
  17. HTML Meta tags for search engines
    - Meta tags used for page indexing optimization in search engines, content, description, keywords, author, alternate. Meta redirect.
  18. HTML object and param
    - How to embed media content (such as an image, Java applet, movie, audio, SWF Flash, PDF files, or even another HTML file) on a web page. Adding Param properties to <object>...</object>.
  19. XHTML vs HTML
    - Differences between XHTML and HTML, XHTML syntax rules.
  20. Colors - Codes and Names
    - Colors in the web page, their hexadecimal and RGB Codes, combinations of red, green, blue, color Names.
  21. HTML Symbol Entities
    - Symbol Entities supported by HTML, mathematical symbols, Latin characters, Greek letters, other entities.

PHP Mysql Online Training Course Index


PHP programming and MySQL database

PHP is an open source, server-side web-scripting language that is compatible with all the major web servers (most notably Apache) and databases.
By the help of PHP code you can create dynamic website content. Dynamic Web sites are flexible applications than merely sites.
If you know HTML, but you have no experience in the field of programming, you can easily learn PHP and MySQL with the help of this course.
This course starts from the most simple, explaining the operations of the PHP language, and then move on to detail how to create PHP programs, how to load the PHP scripts, and to the final approach more complex items, such as SQL commands, working with MySQL database, using classes and OOP (Object Oriented Programming) in PHP.
The tutorials covered in this course approach in an easy and intuitive manner with numerous examples that make it easier and more understanding to learn PHP.


Lessons index

PHP Basic (beginner)

1. Writing PHP scripts
      - Writing PHP scripts, learn about PHP code structure, how to write and execute a simple PHP script and to add comments within your code.
2. Variables and Data Types
      - Learn about Variables, values and Data Types in PHP: boolean, integer, float, string, array, object, Resource, null.
3. Numbers and mathematical 0perators
      - Introducing Numbers and mathematical 0perators, some PHP functions for more complex operations with numbers.
4. PHP Strings
      - Working with strings, using simple and double quotes, escaping quotes and other characters, concatenating strings, some functions for strings.
5. Constants
      - Introducing Constants, syntax for defining constants, differences between variables and defined constants.
6. Superglobal $_SERVER Array
      - Get information such as headers, paths, and script locations by using elements from Superglobal $_SERVER Array.
7. PHP Error Handling and Debugging
      - PHP MySQL course - Error Handling, debugging and trigger errors and how to adjust the level of error reporting, handling exceptions.
8. If ... Else conditionals, Comparative and Logical operators
      - Make PHP script takes decisions with If, Else, Elseif conditional statements. Compare two values with Comparative and Logical operators. The ternary operator.
9. Using HTML Forms
      - Using HTML Forms, PHP form handling, get data sent from form fields through GET and POST method, form validation.
10. $_GET, $_POST and $_REQUEST Variables
      - How to send data with get and post methods to a PHP script and access it with superglobal $_GET, $_POST and $_REQUEST variables.
11. Switch ... Case ...
      - PHP MySQL course - Switch ... Case ... conditional statement, switch with break and default instructions.
12. While Loops
      - Using While and Do Wile Loops. End the While loops with the break instruction. Syntax and examples.
13. For and Foreach Loops
      - Using for() and foreach() Loops. End the "For" loops with the break instruction. Syntax and examples.
14. PHP Arrays
      - Creating Numeric (indexed) Arrays and Associative arrays. Accessing, modifying and traversing array elements.
15. Multidimensional arrays and array functions
      - Creating and working with multidimensional arrays, some array functions, traversing and sorting multidimensional array elements.
16. PHP functions
      - Creating and using your own functions with or without parameters, calling functions, the return statement, recursive functions.
17. Functions, Variable scope and Passing by Reference
      - Variable scope and Functions. Using GLOBAL and STATIC variables, passing variables by Reference.

PHP Advanced

18. PHP Anonymous functions - Closures
      - About Anonymous Functions, also known as Closures, how to create and use closures.
19. Include and Require
      - Insert the content of external files into a PHP file with Include and Require functions, include_once, require_once.
20. File Handling with fopen
      - File Handling with fopen(), create new file, write and read text file content with fopen(), fwrite(), fread() and fgets() functions. Moving the internal pointer, rewind() and fseek().
21. File Upload
      - This lesson shows how to upload files on the server, with PHP and an HTML form. Uploading files script.
22. Exploring Folders
      - Exploring the Folder system, creating folders with PHP, reading a directory content. Get information about a file path.
23. Cookies
      - Setting and accesing cookies with PHP, retrieve a Cookie value, deleting cookies.
24. Sessions
      - Setting and handling Session variables. Accessing and deleting session, destroy sessions. Store encrypted data in sessions.
25. RegExp - Regular Expressions
      - RegExp patterns - Regular Expressions. Examples with preg_match, preg_match_all, and preg_replace functions for string matching and string substituting operations.
26. Date and Time
      - Date and Time functions, handle date and time information, UNIX timestamp, set and get time values.
27. DateTime and DateTimeZone classes
      - Handle date and time information with PHP DateTime and DateTimeZone classes and objects, reset /change Timezone, get the difference between two dates.
28. Sending E-mails
      - Sending E-mails, mail() function. Create a mail contact form script, validate e-mail address, filter input email data, and add the "From", "Conten-Type" (utf-8), and "Reply-To" headers in the email.

PHP MySQL

29. PHP MySQL Introduction, Data Types
      - PHP MySQL Introduction, database structure, tables. MySQL naming rules, and column's data types.
30. PHP MySQL - using MySQLi
      - Using MySQLi object-oriented (MySQL Improved) to connect to MySQL server. Perform SQL queries to create a database and tables.
31. PHP MySQL - INSERT INTO
      - Insert data in MySQL table with MySQLi object, INSERT INTO query. Get the auto ID from the last INSERT query with insert_id() method. Insert data from a form into a database.
32. PHP MySQL - SELECT, ORDER BY
      - Retrieve and display data from a MySQL table, SELECT SQL command. Determine the number of records to return with the LIMIT option. Sort query results with ORDER BY clause (ASC and DESC).
33. PHP MySQL - WHERE and LIKE
      - Selecting specific data from a database with the WHERE clause and Conditionals. Check for string matching with LIKE and NOT LIKE terms.
34. PHP MySQL - UPDATE
      - UPDATE query to edit / change existing records in MySQL table.
35. PHP MySQL - DELETE
      - The DELETE statement, used to entirely remove records from a database table.
36. MySQL Aliases and Functions
      - Using MySQL Aliases and functions, text, numeric / mathematical, and date and time functions.

PHP PDO - MySQL

37. PHP PDO - Introduction and Connecting to Databases
      - Introduction to PHP PDO, Connecting to various databases, MySQL, PostgreSQL, SQLite, Firebird, MS-Access.
38. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL
      - Using the exec() method to perform MySQL query, INSERT, UPDATE, DELETE.
39. PHP PDO - Select query, fetch
      - Select data in a MySQL table using the PDO query method, and FETCH constants.
40. PHP PDO - prepare and execute
      - How to use the prepare() and execute() methods to perform SQL queries, bindParam, and bindValue.
41. PHP PDO - setAttribute, beginTransaction and commit
      - setAttribute(), beginTransaction(), and commit(). Determine how to handle the errors, and execute multiple different SQL queries.

OOP - Classes and Objects

42. OOP - Creating Classes and Objects
      - OOP (object-oriented programming), creating classes and objects. Setting properties and methods in a class, with public, private or protected attribute. Instantiate an object of a class.
43. OOP - Constructor Method
      - Creating classes with a Constructor Method, __construct(). Setting optional parameters in a constructor method.
44. PHP OOP - Accessor and Destructor methods
      - How to use Accessor methods to set and get property values, defining Destructor methods. PHP functions for checking data type.
45. OOP - Constants, Static Properties and Methods
      - Defining and accessing class Constants, Static Properties and Static Methods.
46. OOP - Inheritance, class extends
      - Inheritance, learn how to extend a class, create subclasses (child classes) that inherit all of the public and protected methods from a parent class. Overriding methods.
47. OOP - Final Classes and Methods
      - OOP - Final Classes and Methods, how to create a class that cannot be extended, and methods that cannot be overridden.
48. Magic Methods __get, __set, __call, __toString
      - About Magic (or interceptor) Methods and their utility in classes, __get, __set, __call, __toString.
49. OOP - Abstract classes
      - Creating Abstract classes and methods, extends an abstract class.
50. PHP OOP - Interfaces
      - Interface, a special class used like a template for classes, defines the methods required in a group of similar classes.
51. Functions with Object and Array arguments
      - How to set functions to accept only certain data type for its parameters, Object and Array arguments.

PHP - DOMDocument - HTML

52. getElementById and getElementsByTagName
      - Learn how to get HTML elements from a HTML document using getElementById() and getElementsByTagName(), methods of the DOMDocument class.
53. Working with HTML attributes in PHP
      - Learn how to use the functions of the DOMElement class to read, set and remove attributes in HTML elements; getAttribute(), hasAttribute(), setAttribute(), and removeAttribute().

PHP - XML

54. XML Documents
      - XML Documents, a brief introduction of initiation, the syntax and structure of an XML document. XML and DTD (Document Type Definition).
55. PHP XML DOM
      - Creating XML documents with PHP XML DOM (Document Object Model), DomDocument object, read and modify data in XML documents.
56. SimpleXML
      - PHP MySQL course - Using the SimpleXML functions to read and modify XML content.

Thursday, 21 March 2013

What's the difference between a programming language, a scripting language, and a markup language?

This is easier to explain in sequence from simple to complex (although it isn't a hierarchy), and the categories aren't as fixed as they appear. The best definitions can be found in the venerable Portland Pattern Repository, but this is my understanding of the terms, as far as it is possible to define them within the last few decades of computer history:

Markup languages
Crucially, these languages (HTML, CSS, XML...) have no logic, and are for marking up text or data in logical groupings (e.g. XML), and/or for setting and storing (typically) property:value pairs (e.g. CSS).

Scripting languages
There is no firm category of 'scripting' languages, but the term is often used to indicate (as nathanator11 states) easy-to-use languages at a higher level than compiled languages like C. Perl, Python, Ruby and PHP are often called scripting languages, partly because the write-compile-run cycle is shortened to write-run, as the language runs via an interpreter that turns the English-like code you write into something the computer can understand. However, boundaries are blurred because some languages can be both interpreted and compiled. Yet, from the programmer's point of view, the main difference is the lack of a need to explicitly compile, and hence the development process is (theoretically) shortened. Some 'scripting' languages can be modified while they are actually running. Although there may appear to be a long route from (say) Unix shell scripting to (say) Perl and Ruby, there's a continuum of features that each borrows of inherits from its predecessors. Another crucial factor in scripting languages is that they do not (usually) deal with such things as memory allocation.

In the days before high level languages (further removed from the 'metal' or lower-level code of the machine itself) there wasmachine code and assembly language; following the advent of high-level languagesscripting was a term often reserved for enhancements to existing functionality, or to carry out small repetitive tasks, yet it still covered a wide range - Visual Basic, Javascript and Logo have all been called 'scripting' languages.

Programming or compiled languages
Typically, the category 'programming languages' covers all languages that contain logic to control whatever you want to do with a computer, so 'scripting' languages are also included. However, some of these languages need to be compiled (see above) from the code you type in to machine instructions, so the need to compile a language puts it in a separate category. As a rough guide, any language that can directly manipulate the lower-level workings of the computer is most likely not going to be called a scripting language.

What is the different between mark-up languages and scripting languages?

Scripting languages are interpreted at run-time. This means that every time you want to run the program, a separate program needs to read the code, interpret it, and then follow the instructions in the code. Compiled code has already been interpreted into machine language, so it is will typically execute faster because the conversion into machine language has already been done. 

Markup languages (HTML, XML) are somewhat different from both of the others. A markup language is simply a set of tags that are used to "mark up" text documents so that sections of text can be logically arranged and labeled. These documents can be viewed as plain text, or, more commonly, are viewed through a browser. The browser parses the document, looking for markup tags, and it then arranges the text and/or formats it according to the values in the tags.

Wednesday, 20 March 2013

Difference Between PHP and ASP .Net


Whenever there is a need for inter-linking hugely databases to generate database driven websites, web programmers or web developers unanimously agree on using PHP programming oASP.Net programming. ASP ( Active-server-pages) and PHP ( Hyper text preprocessor) are considered as the two most popular and standard web programming languages because of their unique advantages over other web development languages. Both ASP.Net and PHP are developed to provide support to dynamic database driven websites. ASP.Net works smoothly on Microsoft products and it can be used with only IIS (Internet Information Server); whereas PHP can be run on any kind of platform as well as it can be connected with different types of databases.
ASP.Net is comparatively new programming language which was launched in 2002 by Microsoft. This web development language is best for building web applications, web services and dynamic websites. On the other hand PHP was launched in 1995 by Rasmus Lerdorf. It is an open source software and it can be downloaded for free under the PHP license. PHP and ASP.Net have some other differences too, which are elaborated below:


The most noteworthy differences include:
  • price
  • platform compatibility
  • developer community
  • speed
  • Database Compatibility
    As PHP uses MySQL for the purpose of database connectivity, it is highly flexible in nature. Another important fact is that it will incur extra expenditure because MySQL can be accessed for free. Whereas, ASP.Net uses MS-SQL for connecting database but MS-SQL can not be availed free from Microsoft.
  • Cost
    Linux can be used for running PHP programs and Linux is free operating system. Therefore, the cost of developing a website in PHP language is remarkably low. On the other hand, you need to install Internet Information Server (IIS)on a Windows server platform if you want to run ASP.Net program. As Windows server platform is not a free product, the cost of production is bounded to be increased.
  • General Run Time
    It has been observed that ASP.Net code runs slower than PHP code. This is because ASP.Net utilizes server space while running whereas inbuilt memory space is used by PHP while running.
  • Coding Simplicity
    ASP.Net codes are somewhat complicated and a web developer needs to work hard to get the hang of it. But PHP codes are very simple and a programmer does not have to make a diligent effort because it is comparatively easier than other types of programming languages.
  • Platform Connectivity Issue
    ASP codes are usually run on Windows platforms but if you install ASP-Apache in the server than it can run on Linux platform as well. PHP has a unique advantage in this issue. Its codes can be linked with different types of platforms such as Windows, Linux and UNIX.
  • Cost of Tools
    PHP codes are available for free in various forums and blogs as it is a open source software. Furthermore, some useful tools that can be used in PHP are also available for free. However, no such free tools are available for ASP.Net.
  • Background Language Support
    The codes that are used in PHP are very much similar to that of C++ language and its syntax resembles the syntax used in C and C++. Therefore, if you have a fair knowledge in C++ or C, you will not face any difficulty while coding PHP language. However, the syntax of ASP is more or less similar to that of Visual basic syntax and this is all but simple.
  • Security
    Though PHP can offer enough measures for ensuring data security, ASP. Net is reputed for creating sophisticated techniques to ensure the safety of confidential data. This is the reason why government organizations opt for ASP.Net.
Our programmers at Quality Web Programming are expert and extremely efficient in developing websites based on PHP and ASP.Net programming language. You can view our portfolio section for assessing the quality of our PHP programming services and ASP.Net programming service.


PHP 4PHP 5ASP.net
Software pricefreefreefree
Platform pricefreefree$$
Speedstrongstrongweak
Efficiencystrongstrongweak
Securitystrongstrongstrong
Platformstrongstrongweak (IIS only)
Platformanyanywin32 (IIS only)
Source availableyesyesno
Exceptionsnoyesyes
OOPweakstrongstrong