MySql Tutorial

The MySQL Configuration File: my.cnf

This file, entitled my.cnf, stores default startup options for both the server and for clients. Correct configuration of this file can go a long way towards optimizing MySQL, as various memory buffer settings and other valuable options can be set here.

Interestingly, the scope of this file can be set according to its location. The settings will be considered global to all MySQL servers if stored in /etc/my.cnf. It will be global to a specific server if located in the directory where the MySQL databases are stored (/usr/local/mysql/data for a binary installation, or /usr/local/var for a source installation). Finally, its scope could be limited to a specific user if located in the home directory of the MySQL user (~/.my.cnf). Keep in mind that even if MySQL does locate a my.cnf file in /etc/my.cnf (global to all MySQL servers on that machine), it will continue its search for a server-specific file, and then a user-specific file. You can think of the final configuration settings as being the result of the /etc/my.cnf, mysql-data-dir/my.cnf, and ~/.my.cnf files.

MySQL Table Types

MySQL supports various of table types or storage engines to allow you to optimize your database. The table types are available in MySQL are:

  • ISAM
  • MyISAM
  • InnoDB
  • BerkeleyDB (BDB)
  • MERGE
  • HEAP

The most important feature to make all the table types above distinction is transaction-safe or not. Only InnoDB and BDB tables are transaction safe and only MyISAM tables support full-text indexing and searching feature. MyISAM is also the default table type when you create table without declaring which storage engine to use. Here are some major features of each table types:

ISAM

ISAM had been deprecated and removed from version 5.x. All of it functionality entire replace by MyISAM. ISAM table has a hard size 4GB and is not portable.

MyISAM

MyISAM table type is default when you create table. MyISAM table work very fast but not transaction-safe. The size of MyISAM table depends on the operating system and the data file are portable from system to system. With MyISAM table type, you can have 64 keys per table and maximum key length of 1024 bytes.

InnoDB

Different from MyISAM table type, InnoDB table are transaction safe and supports row-level locking. Foreign keys are supported in InnoDB tables. The data file of InnoDB table can be stored in more than one file so the size of table depends on the disk space. Like the MyISAM table type, data file of InnoDB is portable from system to system. The disadvantage of InnoDB in comparison with MyISAM is it take more disk space.

BDB

BDB is similar to InnoDB in transaction safe. It supports page level locking but data file are not portable.

MERGE

Merge table type is added to treat multiple MyISAM tables as a single table so it remove the size limitation from MyISAM tables.

HEAP

Heap table is stored in memory so it is the fastest one. Because of storage mechanism, the data will be lost when the power failure and sometime it can cause the server run out of memory. Heap tables do not support columns with AUTO_INCREMENT, BLOB and TEXT characteristics.

MySQL Data Types

Numeric Data Types

You can find all SQL standard numeric types in MySQL including exact number data type and approximate numeric data types including integer, fixed-point and floating point. In addtion, MySQL also supports BIT data type for storing bit field values. Numeric types can be signed or unsigned except BIT type. The following table shows you the summary of numeric types in MySQL:

Numeric Types Description
TINYINT A very small integer
SMALLINT A small integer
MEDIUMINT A medium-sized integer
INT A standard integer
BIGINT A large integer
DECIMAL A fixed-point number
FLOAT A single-precision floating-point number
DOUBLE A double-precision floating-point number
BIT A bit field

String Data Types

In MySQL, string can hold anything from plain text to binary data such as images and files. String can be compared and searched based on pattern matching by using LIKE clause or regular expression. The table below shows you the string data types in MySQL:

String Types Description
CHAR A fixed-length non-binary (character) string
VARCHAR A variable-length non-binary string
BINARY A fixed-length binary string
VARBINARY A variable-length binary string
TINYBLOB A very small BLOB (binary large object)
BLOB A small BLOB
MEDIUMBLOB A medium-sized BLOB
LONGBLOB A large BLOB
TINYTEXT A very small non-binary string
TEXT A small non-binary string
MEDIUMTEXT A medium-sized non-binary string
LONGTEXT A large non-binary string
ENUM An enumeration; each column value may be assigned one enumeration member
SET A set; each column value may be assigned zero or more set members

Date and Time Data Types

MySQL provides types for date and time and combination of date and time. In addition, MySQL also provide timestamp data type for tracking last change on a record. If you just want to store the year without date and month, you can use YEAR data type. Here is the table which showing MySQL date and type data types:

Date and Time Types Description
DATE A date value in ‘CCYY-MM-DD’ format
TIME A time value in ‘hh:mm:ss’ format
DATETIME A date and time value in ‘CCYY-MM-DD hh:mm:ss’ format
TIMESTAMP A timestamp value in ‘CCYY-MM-DD hh:mm:ss’ format
YEAR A year value in CCYY or YY format

Spatial Data Types

MySQL support many spatial data types as below table which contains various kind of geometrical and geographical values.

Spatial Data Types Description
GEOMETRY A spatial value of any type
POINT A point (a pair of X Y coordinates)
LINESTRING A curve (one or more POINT values)
POLYGON A polygon
GEOMETRYCOLLECTION A collection of GEOMETRY values
MULTILINESTRING A collection of LINESTRING values
MULTIPOINT A collection of POINT values
MULTIPOLYGON A collection of POLYGON values

Creating Tables

To create table we use the CREATE TABLE statement. The typical form of SQL CREATE TABLE statement is as follows:

1 CREATE TABLE [IF NOT EXISTS] table_name(
2 column_list
3 )
  • MySQL supports IF NOT EXISTS after CREATE TABLE statement to prevent you from error of creating table which already exists on the database server.
  • table_name is the name of table you would like to create. After that, you can define a set of columns which is usually in this form: column_name data_type(size) [NOT] NULL.
  • You can specify the storage engine type you prefer to use for the table. MySQL supports various storage engines such as InnoDB, MyISAM… If you don’t explicit declare storage engine type, MySQL will use MyISAM by default.

In our classicmodels sample database, to create employees table, we can use the CREATE TABLE statement as follows:

01 CREATE TABLE employees (
02 employeeNumber into(11) NOT NULL,
03 lastName varchar(50) NOT NULL,
04 firstName varchar(50) NOT NULL,
05 extension varchar(10) NOT NULL,
06 email varchar(100) NOT NULL,
07 officeCode varchar(10) NOT NULL,
08 reportsTo int(11) default NULL,
09 jobTitle varchar(50) NOT NULL,
10 PRIMARY KEY  (employeeNumber)
11 );

First, you specify table name employees after CREATE TABLE statement.

Then you list the columns of the table with their attributes such as data type, size, NOT NULL.

And finally you specify the primary key of the table, in this case the primary key is employeeNumber.

If the table has more than one primary key, you can seperate them by a comma. For example, the payments table has two primary keys customerNumber and checkNumber. You can create payments table by executing following query:

1 CREATE TABLE payments (
2 customerNumber int(11) NOT NULL,
3 checkNumber varchar(50) NOT NULL,
4 paymentDate datetime NOT NULL,
5 amount double NOT NULL,
6 PRIMARY KEY  (customerNumber,checkNumber)
7 );

Note taht by default MySQL uses MyISAM storage engine for the table it created.

Showing and Describing Tables in a Database

In order to show all tables in a database, you use SHOW TABLES statment. By executing theSHOW TABLES statement, MySQL will returns all tables’ name of the current selected database you’re working with.

1 SHOW TABLES

Here is the output of classicmodels database:

+————————-+

| Tables_in_classicmodels |

+————————-+

| customers               |

| employees               |

| offices                 |

| orderdetails            |

| orders                  |

| payments                |

| productlines            |

| products                |

+————————-+

8 rows in set (0.00 sec)

In some cases, you need to see the table’s metadata, you can use DESCRIBE statement as follows:

1 DESCRIBE table_name;

For instance, we can describe employees table like below query:

1 DESCRIBE employees;

The output return from the database server:

+—————-+————–+——+—–+———+——-+

| Field          | Type         | Null | Key | Default | Extra |

+—————-+————–+——+—–+———+——-+

| employeeNumber | int(11)      | NO   | PRI | NULL    |       |

| lastName       | varchar(50)  | NO   |     | NULL    |       |

| firstName      | varchar(50)  | NO   |     | NULL    |       |

| extension      | varchar(10)  | NO   |     | NULL    |       |

| email          | varchar(100) | NO   |     | NULL    |       |

| officeCode     | varchar(10)  | NO   |     | NULL    |       |

| reportsTo      | int(11)      | YES  |     | NULL    |       |

| jobTitle       | varchar(50)  | NO   |     | NULL    |       |

+—————-+————–+——+—–+———+——-+

8 rows in set (0.02 sec)

Jquery Tutorial

jQuery is a JavaScript Library
The jQuery library contains the following features:
• HTML element selections
• HTML element manipulation
• CSS manipulation
• HTML event functions
• JavaScript Effects and animations
• HTML DOM traversal and modification
• AJAX
• Utilities
jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).
Basic syntax is: $(selector).action()
• A dollar sign to define jQuery
• A (selector) to “query (or find)” HTML elements
• A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() – hides current element
$(“p”).hide() – hides all paragraphs
$(“p.test”).hide() – hides all paragraphs with class=”test”
$(“#test”).hide() – hides the element with id=”test”
The Document Ready Function
You might have noticed that all jQuery methods, in our examples, are inside a document.ready() function:
$(document).ready(function(){

// jQuery functions go here…

});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
Here are some examples of actions that can fail if functions are run before the document is fully loaded:
• Trying to hide an element that doesn’t exist
• Trying to get the size of an image that is not loaded

jQuery Element Selectors
jQuery uses CSS selectors to select HTML elements.
$(“p”) selects all

elements.
$(“p.intro”) selects all

elements with class=”intro”.
$(“p#demo”) selects all

elements with id=”demo”.
________________________________________
jQuery Attribute Selectors
jQuery uses XPath expressions to select elements with given attributes.
$(“[href]“) select all elements with an href attribute.
$(“[href='#']“) select all elements with an href value equal to “#”.
$(“[href!='#']“) select all elements with an href attribute NOT equal to “#”.
$(“[href$='.jpg']“) select all elements with an href attribute that ends with “.jpg”.
________________________________________
jQuery CSS Selectors
jQuery CSS selectors can be used to change CSS properties for HTML elements.
The following example changes the background-color of all p elements to yellow:
Example
$(“p”).css(“background-color”,”yellow”);

Some More Examples
Syntax Description
$(this) Current HTML element
$(“p”) All

elements
$(“p.intro”) All

elements with class=”intro”
$(“p#intro”) All

elements with id=”intro”
$(“p#intro:first”) The first

element with id=”intro”
$(“.intro”) All elements with class=”intro”
$(“#intro”) The first element with id=”intro”
$(“ul li:first”) The first

element of each

$(“[href$='.jpg']“) All elements with an href attribute that ends with “.jpg”
$(“div#intro .head”) All elements with class=”head” inside a element with id=”intro”

jQuery Name Conflicts
jQuery uses the $ sign as a shortcut for jQuery.
Some other JavaScript libraries also use the dollar sign for their functions.
The jQuery noConflict() method specifies a custom name (like jq), instead of using the dollar sign.

jQuery Events
Here are some examples of event methods in jQuery:
Event Method Description
$(document).ready(function) Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function) Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function) Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function) Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function) Triggers, or binds a function to the mouseover event of selected elements

jQuery Effects
Here are some examples of effect functions in jQuery:
Function Description
$(selector).hide() Hide selected elements
$(selector).show() Show selected elements
$(selector).toggle() Toggle (between hide and show) selected elements
$(selector).slideDown() Slide-down (show) selected elements
$(selector).slideUp() Slide-up (hide) selected elements
$(selector).slideToggle() Toggle slide-up and slide-down of selected elements
$(selector).fadeIn() Fade in selected elements
$(selector).fadeOut() Fade out selected elements
$(selector).fadeTo() Fade out selected elements to a given opacity
$(selector).animate() Run a custom animation on selected elements

jQuery HTML Manipulation

jQuery contains powerful methods (functions) for changing and manipulating HTML elements and attributes.
________________________________________
Changing HTML Content
$(selector).html(content)
The html() method changes the contents (innerHTML) of matching HTML elements.
Example
$(“p”).html(“W3Schools”);

jQuery HTML Manipulation Methods From This Page:
Function Description
$(selector).html(content) Changes the (inner) HTML of selected elements
$(selector).append(content) Appends content to the (inner) HTML of selected elements
$(selector).after(content) Adds HTML after selected elements

jQuery CSS Methods From this Page:
CSS Properties Description
$(selector).css(name) Get the style property value of the first matched element
$(selector).css(name,value) Set the value of one style property for matched elements
$(selector).css({properties}) Set multiple style properties for matched elements
$(selector).height(value) Set the height of matched elements
$(selector).width(value) Set the width of matched elements

jQuery Selectors
Use our excellent jQuery Selector Tester to experiment with the different selectors.
Selector Example Selects
*
$(“*”) All elements
#id
$(“#lastname”) The element with id=lastname
.class
$(“.intro”) All elements with class=”intro”
element
$(“p”) All p elements
.class.class $(“.intro.demo”) All elements with the classes “intro” and “demo”

:first
$(“p:first”) The first p element
:last
$(“p:last”) The last p element
:even
$(“tr:even”) All even tr elements
:o dd
$(“tr:odd”) All odd tr elements

:eq(index)
$(“ul li:eq(3)”) The fourth element in a list (index starts at 0)
:gt(no)
$(“ul li:gt(3)”) List elements with an index greater than 3
:lt(no)
$(“ul li:lt(3)”) List elements with an index less than 3
:not(selector)
$(“input:not(:empty)”) All input elements that are not empty

:header
$(“:header”) All header elements h1, h2 …
:animated
$(“:animated”) All animated elements

:contains(text)
$(“:contains(‘W3Schools’)”) All elements which contains the text
:empty
$(“:empty”) All elements with no child (elements) nodes
:hidden $(“p:hidden”) All hidden p elements
:visible
$(“table:visible”) All visible tables

s1,s2,s3 $(“th,td,.intro”) All elements with matching selectors

[attribute]
$(“[href]“) All elements with a href attribute
[attribute=value]
$(“[href='default.htm']“) All elements with a href attribute value equal to “default.htm”
[attribute!=value]
$(“[href!='default.htm']“) All elements with a href attribute value not equal to “default.htm”
[attribute$=value]
$(“[href$='.jpg']“) All elements with a href attribute value ending with “.jpg”

:input
$(“:input”) All input elements
:text
$(“:text”) All input elements with type=”text”
:password
$(“:password”) All input elements with type=”password”
:radio
$(“:radio”) All input elements with type=”radio”
:checkbox
$(“:checkbox”) All input elements with type=”checkbox”
:submit
$(“:submit”) All input elements with type=”submit”
:reset
$(“:reset”) All input elements with type=”reset”
:button
$(“:button”) All input elements with type=”button”
:image
$(“:image”) All input elements with type=”image”
:file
$(“:file”) All input elements with type=”file”

:enabled
$(“:enabled”) All enabled input elements
:disabled
$(“:disabled”) All disabled input elements
:selected
$(“:selected”) All selected input elements
:checked
$(“:checked”) All checked input elements

jQuery Event Methods
Event methods trigger, or bind a function to an event for all matching elements.
Trigger example:
$(“button”).click() – triggers the click event for a button element.
Binding example:
$(“button”).click(function(){$(“img”).hide()}) – binds a function to the click event.
The following table lists all the methods used to handle events.
Method Description
bind()
Add one or more event handlers to matching elements
blur()
Triggers, or binds a function to the blur event of selected elements
change()
Triggers, or binds a function to the change event of selected elements
click()
Triggers, or binds a function to the click event of selected elements
dblclick()
Triggers, or binds a function to the dblclick event of selected elements
delegate()
Add one or more event handlers to current, or future, specified child elements of the matching elements
die()
Remove all event handlers added with the live() function
error()
Triggers, or binds a function to the error event of selected elements
event.currentTarget The current DOM element within the event bubbling phase
event.data Contains the optional data passed to jQuery.fn.bind when the current executing handler was bound
event.isDefaultPrevented()
Returns whether event.preventDefault() was called for the event object
event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was called for the event object
event.isPropagationStopped() Returns whether event.stopPropagation() was called for the event object
event.pageX
The mouse position relative to the left edge of the document
event.pageY
The mouse position relative to the top edge of the document
event.preventDefault()
Prevents the default action of the event
event.relatedTarget The other DOM element involved in the event, if any
event.result
This attribute contains the last value returned by an event handler that was triggered by this event, unless the value was undefined
event.stopImmediatePropagation() Prevents other event handlers from being called
event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
event.target
The DOM element that initiated the event
event.timeStamp
This attribute returns the number of milliseconds since January 1, 1970, when the event is triggered
event.type
Describes the nature of the event
event.which
Which key or button was pressed for a key or button event
focus()
Triggers, or binds a function to the focus event of selected elements
focusin()
Binds a function to the focusin event of selected elements
focusout()
Binds a function to the focusout event of selected elements
hover()
Binds one or two functions to the hover event of selected elements
keydown()
Triggers, or binds a function to the keydown event of selected elements
keypress()
Triggers, or binds a function to the keypress event of selected elements
keyup()
Triggers, or binds a function to the keyup event of selected elements
live()
Add one or more event handlers to current, or future, matching elements
load()
Triggers, or binds a function to the load event of selected elements
mousedown()
Triggers, or binds a function to the mouse down event of selected elements
mouseenter()
Triggers, or binds a function to the mouse enter event of selected elements
mouseleave()
Triggers, or binds a function to the mouse leave event of selected elements
mousemove()
Triggers, or binds a function to the mouse move event of selected elements
mouseout()
Triggers, or binds a function to the mouse out event of selected elements
mouseover()
Triggers, or binds a function to the mouse over event of selected elements
mouseup()
Triggers, or binds a function to the mouse up event of selected elements
one()
Add one or more event handlers to matching elements. This handler can only be triggered once per element
ready()
Binds a function to the ready event of a document
(when an HTML document is ready to use)
resize()
Triggers, or binds a function to the resize event of selected elements
scroll()
Triggers, or binds a function to the scroll event of selected elements
select()
Triggers, or binds a function to the select event of selected elements
submit()
Triggers, or binds a function to the submit event of selected elements
toggle()
Binds two or more functions to the toggle between for the click event for selected elements
trigger()
Triggers all events bound to the selected elements
triggerHandler()
Triggers all functions bound to a specified event for the selected elements
unbind()
Remove an added event handler from selected elements
undelegate()
Remove an event handler to selected elements, now or in the future
unload()
Triggers, or binds a function to the unload event of selected elements

jQuery Effect Methods
The following table lists all the methods used to create animation effects.
Method Description
animate()
Performs a custom animation (of a set of CSS properties) for selected elements
clearQueue()
Removes all queued functions for the selected element
delay() Sets a delay for all queued functions for the selected element
dequeue() Runs the next queued functions for the selected element
fadeIn()
Gradually changes the opacity, for selected elements, from hidden to visible
fadeOut()
Gradually changes the opacity, for selected elements, from visible to hidden
fadeTo()
Gradually changes the opacity, for selected elements, to a specified opacity
fadeToggle()
hide()
Hides selected elements
queue() Shows the queued functions for the selected element
show()
Shows hidden selected elements
slideDown()
Gradually changes the height, for selected elements, from hidden to visible
slideToggle()
Toggles between slideUp() and slideDown() for selected elements
slideUp()
Gradually changes the height, for selected elements, from visible to hidden
stop()
Stops a running animation on selected elements
toggle()
Toggles between hide() and show(), or custom functions, for selected elements

jQuery HTML Methods
The following table lists all the methods used to manipulate the DOM.
The methods below work for both HTML and XML documents. Exception: the html() method.
Method Description
addClass()
Adds one or more classes (for CSS) to selected elements
after()
Inserts content after selected elements
append()
Inserts content at the end of (but still inside) selected elements
appendTo()
Inserts content at the end of (but still inside) selected elements
attr()
Sets or returns an attribute and value of selected elements
before()
Inserts content before selected elements
clone()
Makes a copy of selected elements
detach()
Removes (but keeps a copy of) selected elements
empty()
Removes all child elements and content from selected elements
hasClass()
Checks if any of the selected elements have a specified class (for CSS)
html()
Sets or returns the content of selected elements
insertAfter()
Inserts HTML markup or elements after selected elements
insertBefore()
Inserts HTML markup or elements before selected elements
prepend()
Inserts content at the beginning of (but still inside) selected elements
prependTo()
Inserts content at the beginning of (but still inside) selected elements
remove()
Removes selected elements
removeAttr()
Removes an attribute from selected elements
removeClass()
Removes one or more classes (for CSS) from selected elements
replaceAll()
Replaces selected elements with new content
replaceWith()
Replaces selected elements with new content
text()
Sets or returns the text content of selected elements
toggleClass()
Toggles between adding/removing one or more classes (for CSS) from selected elements
unwrap()
Removes the parent element of the selected elements
val()
Sets or returns the value attribute of the selected elements (form elements)
wrap()
Wraps specified HTML element(s) around each selected element
wrapAll()
Wraps specified HTML element(s) around all selected elements
wrapInner()
Wraps specified HTML element(s) around the content of each selected element

jQuery CSS Methods
The following table lists all the methods used to manipulate CSS properties.
Method Description
addClass()
Adds one or more classes to selected elements
css()
Sets or returns one or more style properties for selected elements
hasClass()
Checks if any of the selected elements have a specified class
height()
Sets or returns the height of selected elements
offset()
Sets or returns the position (relative to the document) for selected elements
offsetParent()
Returns the first parent element that is positioned
position()
Returns the position (relative to the parent element) of the first selected element
removeClass()
Removes one or more classes from selected elements
scrollLeft()
Sets or returns the horizontal position of the scrollbar for the selected elements
scrollTop()
Sets or returns the vertical position of the scrollbar for the selected elements
toggleClass()
Toggles between adding/removing one or more classes from selected elements
width()
Sets or returns the width of selected elements

jQuery AJAX Methods
AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page.
The following table lists all the jQuery AJAX methods:
Method Description
$.ajax()
Performs an AJAX request
ajaxComplete()
Specifies a function to run when the AJAX request completes
ajaxError()
Specifies a function to run when the AJAX request completes with an error
ajaxSend()
Specifies a function to run before the AJAX request is sent
$.ajaxSetup()
Sets the default values for future AJAX requests
ajaxStart()
Specifies a function to run when the first AJAX request begins
ajaxStop()
Specifies a function to run when all AJAX requests have completed
ajaxSuccess()
Specifies a function to run an AJAX request completes successfully
$.get()
Loads data from a server using an AJAX HTTP GET request
$.getJSON()
Loads JSON-encoded data from a server using a HTTP GET request
$.getScript()
Loads (and executes) a JavaScript from the a server using an AJAX HTTP GET request
load()
Loads data from a server and puts the returned HTML into the selected element
$.param()
Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post()
Loads data from a server using an AJAX HTTP POST request
serialize()
Encodes a set of form elements as a string for submission
serializeArray()
Encodes a set of form elements as an array of names and values

jQuery Misc Methods
Method Description
data() : Attaches data to, or gets data from, selected elements
each() : Run a function for each element matched by the jQuery selector
get() : Get the DOM elements matched by the selector
index() : Search for a given element from among the matched elements
$.noConflict() : Release jQuery’s control of the $ variable
$.param() : Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
removeData() : Removes a previously-stored piece of data
size() :Return the number of DOM elements matched by the jQuery selector
toArray() : Retrieve all the DOM elements contained in the jQuery set, as an array

TSS Company blog

We are happy to introducing TSS company blog. In this blog we are post technical related posts.

Thanks,
TSS Team