<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Blazej Klisz's Blog</title>
  <updated>2012-06-16T23:39:03+02:00</updated>
  <generator uri="http://framework.zend.com" version="1.10.8">Zend_Feed_Writer</generator>
  <link rel="alternate" type="text/html" href="http://blazejklisz.pl"/>
  <link rel="self" type="application/atom+xml" href="http://blazejklisz.pl/atom.xml"/>
  <id>http://blazejklisz.pl</id>
  <author>
    <name>Blazej Klisz</name>
    <email>the_joshua_tree@o2.pl</email>
    <uri>http://blazejklisz.pl</uri>
  </author>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[MySQL stored programs: cursors]]></title>
    <summary type="html"><![CDATA[Cursor is a handy tool to deal with sets of rows retrieved from select statements` result 
inside stored procedures. Lets look closer to them.]]></summary>
    <published>2012-06-16T23:23:30+02:00</published>
    <updated>2012-06-16T23:29:30+02:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/mysql-stored-programs-cursors"/>
    <id>http://blazejklisz.pl/blog/article/mysql-stored-programs-cursors</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Every cursor must have at least 4 elements named below:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>DECLARE keyword</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>cursor name</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>CURSOR FOR keywords</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>SELECT statement</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>The sample procedure that does nothing more that just creating
cursor, looks like this:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
    CREATE PROCEDURE sample_procedure ()
    BEGIN
            DECLARE 
            cur 
            CURSOR FOR 
            SELECT title FROM film;
    END;
</xhtml:pre>
<xhtml:p>I've put every part in a new line but in a such simple code it's
not recommended. Declaring cursor it's necessary to put it after
all variables declarations. It's just a meter of order that this
code will work:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
        DECLARE str VARCHAR(50);
        DECLARE cur CURSOR FOR SELECT title FROM film;
</xhtml:pre>
<xhtml:p>...and this on will give an error.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
        DECLARE cur CURSOR FOR SELECT title FROM film;
        DECLARE str VARCHAR(50);
</xhtml:pre>
<xhtml:pre class="brush: sql; toolbar: false;">
MySQL Database Error: Variable or condition declaration 
after cursor or handler declaration.
</xhtml:pre>
<xhtml:p>When the cursor is ready we can finally use it. Use of cursor is
based on 3 commands:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>open</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>fetch</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>close</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>The first one and the last one are very simple. When you
starting using cursor just write OPEN cursor_name, where
cursor_name is your real cursor's name. According to this rule:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
OPEN cur;
</xhtml:pre>
<xhtml:p>When the cursor is not needed anymore you can close it by typing
CLOSE cursor_name.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
CLOSE cur;
</xhtml:pre>
<xhtml:p>You can't open cursor when it's open, you can't closed cursor
that isn't open and you can't fetch cursor that is closed. Contrary
to the open and the close commands the fetch is can be quite
complicated. A fetch statement consists of 4 elements:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>FETCH keyword</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>CURSOR name</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>INTO keyword</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>list of variables delimited by a comma</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>In this statement we are dispatching data from query's result to
the variables declared in stored procedure. Most important thing is
to set on a list as many variables as columns return in query -
every column must have its own variable. Below I present next stage
of a procedure's body. I used SELECT to show that the cursor is
working, but obviously it's not necessary.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  DECLARE str VARCHAR(50);
    
  DECLARE cur CURSOR FOR SELECT title FROM film;

  OPEN cur;
  
  FETCH cur INTO str;
  SELECT str;
  CLOSE cur;
</xhtml:pre>
<xhtml:img src="/images/postimages/mysql-stored-procedures-cursors/mysql-cursor-result.JPG"/>
<xhtml:p>OK. Cursor is working, at least in some way, but shouldn`t there
be more that one row (as many as rows in the film table to be
exact)? Of course there should be. So what happened? Cursor was
opened, then value of the first row was inserted into str variable,
the select statement was made and after all of this the cursor was
closed. Probably you are already know that cursor processing must
be more complex when its select query retrieves result set rather
than single row. This is the place where loops came into play. In
MySQL stored programs we can make use of 3 types of loops:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>LOOP - END LOOP</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>WHILE - END WHILE</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>REPEAT UNTIL</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>If you are familiar with some programming language you have
probably meet while and repeat loops. Both of them have conditions
that tells the program when it should leave the loop. Simple
MySQL's loop don't require any type of condition of that type, so
loop in its most basic form will run forever. Code of infinite loop
is below:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  DECLARE i int default 1;
  simple_loop: LOOP
    SELECT i;
    SET i = i + 1;
  END LOOP simple_loop;
</xhtml:pre>
<xhtml:p>When instead showing infinite list of number we put inside the
loop a fetch cursor command we will receive a list of title and an
error...</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  simple_loop: LOOP
    FETCH cur INTO str;
    SELECT str;
  END LOOP simple_loop;
</xhtml:pre>
<xhtml:pre class="brush: sql; toolbar: false;">
    No data - zero rows fetched, selected, or processed
</xhtml:pre>
<xhtml:p>If there is any sense using loop that don't even know where it
have to stop? Of course not, but fortunately we can quickly fix it
with at least 2 ways. First one is based on a counting fetched rows
and comparing current number with number of rows return by query
statement. It can look like this:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  DECLARE str VARCHAR(50);
  DECLARE cnt INT;
  DECLARE i INT DEFAULT 0;
  
  DECLARE cur CURSOR FOR SELECT title FROM film LIMIT 5;
  
  SELECT COUNT(*) FROM film WHERE film_id &lt;= 5 INTO cnt;

  OPEN cur;
  simple_loop: LOOP
    SET i = i + 1;
    
    IF i &gt; cnt THEN
      LEAVE simple_loop;
    END IF;
    
    FETCH cur INTO str;
    SELECT str;
  END LOOP simple_loop;
  CLOSE cur;
</xhtml:pre>
<xhtml:p>The second solution is based on error handling. We have to
define what should happen when there is no more rows. Code below is
shorter, cleaner and will give the same result as before.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  DECLARE str VARCHAR(50);
  DECLARE end_loop INT DEFAULT 0;
  
  DECLARE cur CURSOR FOR SELECT title FROM film LIMIT 5;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET end_loop = 1;

  OPEN cur;
  
  simple_loop: LOOP
    
    FETCH cur INTO str;
    SELECT str;
    
    IF end_loop = 1 THEN
      LEAVE simple_loop;
    END IF;
    
  END LOOP simple_loop;
  
  CLOSE cur;
</xhtml:pre>
<xhtml:p>Remember that declaration of a handler must follow cursor
declaration. Finally our cursor is completed and it's really
working. Next time I'll build the same cursor using two other
loops.</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[MySQL stored programs: functions]]></title>
    <summary type="html"><![CDATA[Since the fifth release of MySQL (5.1 to be exact) programmers have capability to 
use <strong>stored programs (functions, procedures and triggers)</strong>, a feature well known from other 
popular databases. According to the result of my small research it's a nameless subset of 
the <strong>ANSI SQL: 2003 SQL/PSM</strong> specification, very similar to the 
SQL PL (based on the same specification) 
used by DB2 and less similar to  the PL/SQL (Oracle, DB2), 
PL/pgSQL (PostgreSQL) and T-SQL(SQL Server and Sybase).]]></summary>
    <published>2012-04-30T23:16:37+02:00</published>
    <updated>2012-04-30T23:27:22+02:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/mysql-stored-programs-functions"/>
    <id>http://blazejklisz.pl/blog/article/mysql-stored-programs-functions</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Probably you are using functions such as min(), max(), count(),
sum() on a regular basis. Functions written as stored programs
works the in the same way (from a developer's point of view). Most
important features of functions are:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>they can't modify parameters,</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>they return a single value, not a result set,</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>they can be called as a part of SQL statements.</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Functions consists of:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>declaration, which is build from:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>function name,</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>list of parameters,</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>returns statement.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:p>function body, which is build from:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>declarations,</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>processing block,</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>return statement.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Before we go further please make sure you have the sakila sample
database and a SQL query editor. If you don't have the database,
you can download it from <xhtml:a href="http://downloads.mysql.com/docs/sakila-db.zip">here</xhtml:a>. As the
editor I recommend <xhtml:a href="http://www.toadworld.com/DOWNLOADS/Freeware/ToadforMySQLFreeware/tabid/561/Default.aspx">
Toad for MySQL</xhtml:a>. It's free, very comfortable and have a lot of
features. Now lest look at the sakila database. If you are
connected to your MySQL server you should see the Object Explorer
just below the Connection Manager.</xhtml:p>
<xhtml:p class="push_1"><xhtml:img src="/images/postimages/mysql-stored-programs-functions/mysql-stored-programs-functions-toad.png" alt="selectors-comparation"/></xhtml:p>
<xhtml:p>Click on the functions tab and locate the inventory_in_stock
function, click on it, and the click the second image from left
(letter f with blue triangle) - alter the selected function. If
everything went fine, you should see function code on your screen.
Now I'll try comment every line of this code.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
DROP FUNCTION IF EXISTS sakila.get_customer_balance;
</xhtml:pre>
<xhtml:p>If you're altering any stored program you have to first delete
it and than create it. There is no ALTER statement that you may
know from T-SQL. If you are creating function for a first time,
changing its name or you have deleted it manually, you don't have
to use drop statement. Thanks to IF EXISTS part even in situations
that I've listed above it won't cause any errors. Long story short
this line is universal template for creating and altering stored
programs, so memorize it and use it.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
CREATE FUNCTION sakila.`get_customer_balance`(p_customer_id INT, p_effective_date DATETIME) RETURNS decimal(5,2)
</xhtml:pre>
<xhtml:p>It's a very important part so let's split it into pieces:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>CREATE FUNCTION sakila.`get_customer_balance` - this part is
necessary. Every function have to be created and must have a
name.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>(p_customer_id INT, p_effective_date DATETIME) - after a
function name there must be a pair of brackets. If the function
don't have any parameters just leave it empty (). In this example
we see that function takes as parameters two separated by a comma
values: p_customer_id and p_effective_date. First one must be an
integer type, second must be a type of datetime.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>RETURNS decimal(5,2) - in last part we see type declaration of
value returned by the function.</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:pre class="brush: sql; toolbar: false;">
READS SQL DATA
</xhtml:pre>
<xhtml:p>This line means that some data will be retrieved from database,
but nothing will be changed. Other possible values in this place
are: CONTAINS SQL (function have SQL statements that don't read or
modify data), NO SQL (no SQL statements at all), MODIFIES SQL DATA
(data will be modified).</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
DETERMINISTIC
</xhtml:pre>
<xhtml:p>If your function always returns the same value for the same
parameters that means it is deterministic, otherwise it is
nondeterministic. Though wrong declaration can't cause an error it
may mislead SQL optimizer.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
BEGIN
.
.
.
END;
</xhtml:pre>
<xhtml:p>Every block of code must start with BEGIN statement and end with
END;, so do a body of function.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
#OK, WE NEED TO CALCULATE THE CURRENT BALANCE GIVEN A CUSTOMER_ID
</xhtml:pre>
<xhtml:p>Sample comment. As you can see below it can also start after SQL
statement.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  DECLARE v_rentfees DECIMAL(5,2); #FEES PAID TO RENT THE VIDEOS INITIALLY
  DECLARE v_overfees INTEGER;      #LATE FEES FOR PRIOR RENTALS
  DECLARE v_payments DECIMAL(5,2); #SUM OF PAYMENTS MADE PREVIOUSLY
</xhtml:pre>
<xhtml:p>Three declarations of values with its types.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
  SELECT IFNULL(SUM(film.rental_rate),0) INTO v_rentfees
    FROM film, inventory, rental
    WHERE film.film_id = inventory.film_id
      AND inventory.inventory_id = rental.inventory_id
      AND rental.rental_date &lt;= p_effective_date
      AND rental.customer_id = p_customer_id;

  SELECT IFNULL(SUM(IF((TO_DAYS(rental.return_date) - 
                    TO_DAYS(rental.rental_date)) &gt; film.rental_duration,
        ((TO_DAYS(rental.return_date) - TO_DAYS(rental.rental_date)) - 
            film.rental_duration),0)),0) INTO v_overfees
    FROM rental, inventory, film
    WHERE film.film_id = inventory.film_id
      AND inventory.inventory_id = rental.inventory_id
      AND rental.rental_date &lt;= p_effective_date
      AND rental.customer_id = p_customer_id;


  SELECT IFNULL(SUM(payment.amount),0) INTO v_payments
    FROM payment

    WHERE payment.payment_date &lt;= p_effective_date
    AND payment.customer_id = p_customer_id;
</xhtml:pre>
<xhtml:p>Three statements retrieving data. Each of statements use
parameters values p_customer_id and p_effective_data and each
returning query result into a previously declared value. Beside
executing statements you can use loops, conditional statements and
assignments.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
RETURN v_rentfees + v_overfees - v_payments;
</xhtml:pre>
<xhtml:p>Finally function is returning of result of addition v_rentfees
and v_overfrees and subtracting v_peyments.</xhtml:p>
<xhtml:p>You can call this function using simple select query:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT get_customer_balance(16, '2012-00-00 00:00:00');
</xhtml:pre>
<xhtml:p>First function behind you. Of course it's only a part of stored
procedures complexity. Hope you've learned something and I'll have
time soon to write next parts about procedures, triggers, error
handling.</xhtml:p>
<xhtml:p>If you're looking a comprehensive guide strictly about SQL/PSM I
recommend reading MySQL Stored Procedure Programming by Guy
Harrison and Steven Feuerstein. As far as I know it's only book in
this field. It was published in 2006 but and I'm not sure if latest
releases of MySQL didn't added more features, but still it's a good
introduction (with more that 600 pages).</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Basic chart with Raphael and a few learning resources]]></title>
    <summary type="html"><![CDATA[<strong>Raphael</strong> is a much less popular then jQuery or even Mootools. 
    It's harder to find tutorials, help and as far as 
I know there isn't any book about it. Taking that into account I'm putting chart that I've created during 
learning basics of Raphael. One day it may become an alternative for <strong>g.Raphael</strong>
(I can hardly imagine that), 
but at this stage it could be only a starting point or a testing ground. It may help you start your own project 
based on Raphael.js.]]></summary>
    <published>2012-01-29T15:03:01+01:00</published>
    <updated>2012-01-29T17:46:12+01:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/basic-chart-with-raphael-and-a-few-learning-resources"/>
    <id>http://blazejklisz.pl/blog/article/basic-chart-with-raphael-and-a-few-learning-resources</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>For those who are not common with a whole concept cross-browser
SVG generating with a help of JavaScript, please look at Raphael
official site:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:a href="http://raphaeljs.com" title="Raphael offical site">Raphael</xhtml:a></xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>If you think that's impressive enough to spend some time with
this library documentation might be needed:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:a href="http://raphaeljs.com/reference.html" title="Raphael.js documentation">Raphaels documentation</xhtml:a></xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p><xhtml:strong>g.Raphael</xhtml:strong> - plug-in for building charts that
I've mentioned previously. It's nice to create basic line, pie, dot
and bar charts. It look really neat, works great, has a few fine
options so if you are building something own definitely look at its
code.</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:a href="http://g.raphaeljs.com/" title="Raphael.js documentation">g.Raphael - Official charting plugin for
Raphael</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="https://github.com/DmitryBaranovskiy/g.raphael" title="gRaphaels github repository">Github repository</xhtml:a></xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Unfortunately there is no documentation, so if you want to use
it you have to learn from examples` source codes and look at
unofficial references like those two:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:a href="http://xerexen.com/posts/documenting-graphael#" title="">g.Raphael - Official charting plugin for Raphael</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="https://github.com/kennyshen/g.raphael" title="gRaphaels github repository">Github repository</xhtml:a></xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>The second isn't current (latest version number is 0.5) but
gives a nice overview.</xhtml:p>
<xhtml:p>Finally a list of most interesting articles, tutorials and
snippets about Raphael:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:a href="http://dashasalo.com/2011/04/04/creating-a-world-map-with-raphaeljs-svg/" title="Creating a worlsd map with Raphael">Creating a worlsd map
with Raphael</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://www.krazybig.com/2011/05/11/raphael-js-sketch-animation/" title="Raphael.js Sketch Animation">Raphael.js Sketch
Animation</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://www.youtube.com/watch?v=q7KF-Xr6bm8" title="Raphael JS Quickstart">Raphael JS Quickstart</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://ianli.com/sketchpad/" title="Raphael SketchPad">Raphael SketchPad</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://www.benbarnett.net/2010/06/04/export-svg-from-raphael-js-to-create-a-png-bitmap/" title="Export SVG from Raphael JS to create a PNG bitmap">Export
SVG from Raphael JS to create a PNG bitmap</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://www.craic.com/tutorials/javascript/raphael_live/raphael_live.html" title="Raphaels Live examples">Raphaels Live examples</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://www.html5rocks.com/en/tutorials/raphael/intro/" title="Introduction to Raphael.js">Introduction to
Raphael.js</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:a href="http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/" title="An Introduction to the Raphael JS Library">An Introduction
to the Raphael JS Library</xhtml:a></xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Some of them might be little out of date, but still they are
very good source of knowledge.</xhtml:p>
<xhtml:p>Now my chart. It's buggy, messy and not universal but it has
some neat solutions which could be time saving. So <xhtml:a href="http://blazejklisz.pl/examples/raphael_chart.html" title="Chart with Raphael">watch the chart</xhtml:a> and <xhtml:a href="https://github.com/thejoshuatree/raphael_chart" title="Code of chart on Github">grab the code on Github</xhtml:a>.</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[JavaScript's and PHP's grid tools]]></title>
    <summary type="html"><![CDATA[Some time ago I was doing a research on grids. I've found not only a couple of grid's plug-ins but also 
a grids that are part of comprehensive tools for RIA development.]]></summary>
    <published>2011-11-27T13:21:08+01:00</published>
    <updated>2011-11-27T13:23:42+01:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/javascripts-and-phps-grid-tools"/>
    <id>http://blazejklisz.pl/blog/article/javascripts-and-phps-grid-tools</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Here it's a summary. I've divided all grids into 4 categories
depending on place of code execution and comprehensiveness of the
library. Some of libraries are mentioned in my previous post about
RIA. Except name and link to the home page of plug-ins/libraries
I'm giving a short information about license and date of the last
update, the most important things beside grid's features.</xhtml:p>
<xhtml:h2 class="post-subtitle">Grid tools written in JavaScript</xhtml:h2>
<xhtml:table class="comp-table">
<xhtml:thead>
<xhtml:tr>
<xhtml:th>Name</xhtml:th>
<xhtml:th>License</xhtml:th>
<xhtml:th>Last update</xhtml:th>
</xhtml:tr>
</xhtml:thead>
<xhtml:tbody>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.trirand.com/blog/" title="jqGrid's homepage">jqGrid</xhtml:a></xhtml:td>
<xhtml:td>GPL and MIT</xhtml:td>
<xhtml:td>November 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://reconstrukt.com/ingrid/" title="ingrid's homepage">ingrid</xhtml:a></xhtml:td>
<xhtml:td>GPL</xhtml:td>
<xhtml:td>November 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="https://github.com/mleibman/SlickGrid" title="SlickGrid's homepage">SlickGrid</xhtml:a></xhtml:td>
<xhtml:td>MIT</xhtml:td>
<xhtml:td>November 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://datatables.net" title="DataTables's homepage">DataTables</xhtml:a></xhtml:td>
<xhtml:td>GPL and BSD</xhtml:td>
<xhtml:td>November 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://tablesorter.com/docs/" title="tablesorter's homepage">tablesorter</xhtml:a></xhtml:td>
<xhtml:td>GPL and MIT</xhtml:td>
<xhtml:td>March 2008</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.sigmawidgets.com/products/sigma_grid2/" title="Sigma Ajax Grid's homepage">Sigma Ajax Grid</xhtml:a></xhtml:td>
<xhtml:td>LGPL and commercial</xhtml:td>
<xhtml:td>April 2010</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://flexigrid.info/" title="flexigrid's homepage">flexigrid</xhtml:a></xhtml:td>
<xhtml:td>GPL and MIT</xhtml:td>
<xhtml:td>May 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://codecanyon.net/item/tquery-dynamic-tables/89478" title="tQuery's homepage">tQuery</xhtml:a></xhtml:td>
<xhtml:td>commertial</xhtml:td>
<xhtml:td/>
</xhtml:tr>
</xhtml:tbody>
</xhtml:table>
<xhtml:h2 class="post-subtitle">Grid tools written in PHP</xhtml:h2>
<xhtml:table class="comp-table">
<xhtml:thead>
<xhtml:tr>
<xhtml:th>Name</xhtml:th>
<xhtml:th>License</xhtml:th>
<xhtml:th>Last update</xhtml:th>
</xhtml:tr>
</xhtml:thead>
<xhtml:tbody>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://phpgrid.com/" title="php Grid's homepage">php
Grid</xhtml:a></xhtml:td>
<xhtml:td>free and commercial</xhtml:td>
<xhtml:td>March 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.phpclasses.org/package/2828-PHP-Edit-and-save-table-data-without-page-refreshing.html" title="AJAX Grid's homepage">AJAX Grid</xhtml:a></xhtml:td>
<xhtml:td>LGPL</xhtml:td>
<xhtml:td/>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.eyesis.ca/projects/datagrid.html" title="Eye Data grid's homepage">Eye Data grid</xhtml:a></xhtml:td>
<xhtml:td>open source</xhtml:td>
<xhtml:td>December 2011</xhtml:td>
</xhtml:tr>
</xhtml:tbody>
</xhtml:table>
<xhtml:h2 class="post-subtitle">Libraries with grids written in
JavaScript</xhtml:h2>
<xhtml:table class="comp-table">
<xhtml:thead>
<xhtml:tr>
<xhtml:th>Name</xhtml:th>
<xhtml:th>License</xhtml:th>
<xhtml:th>Last update</xhtml:th>
</xhtml:tr>
</xhtml:thead>
<xhtml:tbody>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.dhtmlx.com/" title="dhtmlx's homepage">dhtmlx</xhtml:a></xhtml:td>
<xhtml:td>GPL and commercial</xhtml:td>
<xhtml:td>November 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://dojotoolkit.org" title="dojo toolkit's homepage">dojo toolkit</xhtml:a></xhtml:td>
<xhtml:td>BSD and AFL 2.1</xhtml:td>
<xhtml:td>May 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.sencha.com/products/extjs/" title="Ext JS 4's homepage">Ext JS 4</xhtml:a></xhtml:td>
<xhtml:td>GPL and commercial</xhtml:td>
<xhtml:td>October 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.trirand.net/" title="jqGrid's homepage">jqGrid</xhtml:a></xhtml:td>
<xhtml:td>commercial</xhtml:td>
<xhtml:td>November 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://wijmo.com" title="Wijmo's homepage">Wijmo</xhtml:a></xhtml:td>
<xhtml:td>commercial</xhtml:td>
<xhtml:td>October 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://qooxdoo.org" title="qooXdoo's homepage">qooXdoo</xhtml:a></xhtml:td>
<xhtml:td>commercial</xhtml:td>
<xhtml:td>April 2011</xhtml:td>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.bindows.net/" title="Bindows's homepage">Bindows</xhtml:a></xhtml:td>
<xhtml:td>free and commercial</xhtml:td>
<xhtml:td/>
</xhtml:tr>
</xhtml:tbody>
</xhtml:table>
<xhtml:h2 class="post-subtitle">Libraries with grids written PHP</xhtml:h2>
<xhtml:table class="comp-table">
<xhtml:thead>
<xhtml:tr>
<xhtml:th>Name</xhtml:th>
<xhtml:th>License</xhtml:th>
<xhtml:th>Last update</xhtml:th>
</xhtml:tr>
</xhtml:thead>
<xhtml:tbody>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.apphp.com/php-datagrid/index.php" title="apPHP Data Grid's homepage">apPHP Data Grid</xhtml:a></xhtml:td>
<xhtml:td>free and commercial</xhtml:td>
<xhtml:td/>
</xhtml:tr>
<xhtml:tr>
<xhtml:td><xhtml:a href="http://www.koolphp.net/?mod=products&amp;act=view&amp;id=11" title="KoolGrid's homepage">KoolGrid</xhtml:a></xhtml:td>
<xhtml:td>free and commercial</xhtml:td>
<xhtml:td>August 2010</xhtml:td>
</xhtml:tr>
</xhtml:tbody>
</xhtml:table>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[PHP jQuery cookbook review]]></title>
    <summary type="html"><![CDATA[Last week I had an opportunity to read the PHP jQuery cookbook by Vijay Joshi. 
    I love to read and learn 
from on-line resources but when it comes to books I have to admit that I'm a septic.]]></summary>
    <published>2011-11-20T20:26:41+01:00</published>
    <updated>2011-11-20T20:40:50+01:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/php-jquery-cookbook-review"/>
    <id>http://blazejklisz.pl/blog/article/php-jquery-cookbook-review</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>The front page headline says "Over 60 simple but highly
effective recipes to create interactive web applications using PHP
with jQuery", it couldn't be surprise taking into account its
title. Since it's a cookbook not a handbook we have a package of
ready to use solutions rather that tutorials learning what the
JavaScript is. For me as a intermediate jQuery programmer it's a
well title. <xhtml:strong>I don't have to read once again basic topics
about selectors, events and effects.</xhtml:strong></xhtml:p>
<xhtml:p>Most common problem that I have with this type of books is that
the solutions that I count find there not only makes me ponder over
them but sometimes even contradict the knowledge that I have. This
time it is different. From the beginning I've a filling and mental
comfort that the author bases on <xhtml:strong>best practices</xhtml:strong>
that we could be find in many web resources. It helps to straighten
up information I have.</xhtml:p>
<xhtml:ul>
<xhtml:li style="list-style: none; display: inline">
<xhtml:p>For me most interesting recipes were:</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>checking for missing images.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>detecting an AJAX requests.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>aborting AJAX requests.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>loading JavaScript on demand to reduce page load.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>fading element after updating it.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>sending cross-domain requests using server proxy.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>making cross-domain requests with jQuery.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>creating endless scrolling page.</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Beside that it help me to do a small revision of simple XML and
DOM libraries. Recapitulating it's a well written book with
<xhtml:strong>interesting and useful recipes</xhtml:strong> and with really
<xhtml:strong>in-depth explanations</xhtml:strong>. Exactly those explanations
and a form of book as a coherent source of a proven knowledge are
its main advantages.</xhtml:p>
<xhtml:p>Before you buy check table of contents if you need it. If you
do, you shouldn't be disappointed.</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Attaching an event to a form's elements inside an iframe with a use of jQuery.]]></title>
    <summary type="html"><![CDATA[My job was to create a simple form that led people to subscribe to a newsletter. 
Actually the form was ready and all I had to do was to place it on the page and make sure it does it's job. 
I placed the form on the page, styled it and that's where nightmare begun...]]></summary>
    <published>2011-10-30T11:02:05+01:00</published>
    <updated>2011-11-04T22:56:02+01:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/attaching-an-event-to-a-forms-elements-inside-an-iframe-with-a-use-of-jquery"/>
    <id>http://blazejklisz.pl/blog/article/attaching-an-event-to-a-forms-elements-inside-an-iframe-with-a-use-of-jquery</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Did I mentioned that the side where the form belongs was on a
<xhtml:strong>different domain</xhtml:strong> then the target of the form (an
action attribute)? I thought it would be really easy, even if it
wasn't only a pure HTML form because of a unacceptable redirection
to the other side. Just a few lines of jQuery and I've got a nice
asynchronous form that will add any provided e-mail address. It
would be easy if only not the <xhtml:strong>cross domain policy</xhtml:strong>
about which I forgot. An AJAX request didn't sound optimistic at
the time.</xhtml:p>
<xhtml:p>How about <xhtml:a href="http://api.jquery.com/jQuery.getJSON/" title="jQuery getJSON method">$getJSON()</xhtml:a>? Nope, it had to be a POST
method.</xhtml:p>
<xhtml:p>I had to quit with a simple AJAX form, there was no way it could
work. Next I've tried something little more complex an AJAX form
calling a PHP script located on the same domain, which with a use
of a <xhtml:strong>cURL</xhtml:strong> extension should create exactly the same
POST request as a real HTML form, send it to the target and get a
response. It's a popular method to <xhtml:strong>walk around the cross
domain</xhtml:strong> JavaScript's limitations and it's called
<xhtml:strong>proxy</xhtml:strong>. In theory it looks well, but for a some
reason it failed. I had the same values, post arrays looked exactly
the same, even the cookies were identical and all I got was an
application error.</xhtml:p>
<xhtml:p>Here it's my proxy script.</xhtml:p>
<xhtml:pre class="brush: php; toolbar: false;">
    $ch = curl_init();

    $data = array('email' =&gt; 'email@test.com', 
                             'subscription_type' =&gt; 'E', 
                             'id' =&gt; '6', 
                             'extra_ar' =&gt; '');

    curl_setopt($ch, CURLOPT_URL, 'http://www.domain2.com);

    curl_setopt($ch, CURLOPT_USERAGENT, 
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
    $strCookie = 'zenid=2ff8666d6c5f92054a5e0d9f10206bc0; path=/';
    curl_setopt($ch, CURLOPT_COOKIE, $strCookie );
    curl_setopt($ch, CURLOPT_HTTPHEADER, 
                array("Content-Type: application/x-www-form-urlencoded"));
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_HTTPGET, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_exec($ch);
</xhtml:pre>
<xhtml:p>It was time for plan C. <xhtml:strong>Iframe + content
manipulation</xhtml:strong>. As usual it sounds easy and as always it
almost is.</xhtml:p>
<xhtml:ol>
<xhtml:li>
<xhtml:p>Putting a HTML document located on the same server as a parent
document of iframe into iframe went smoothly.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Attaching an event handler to a submit button in the loaded form
turn out not to be obvious.</xhtml:p>
</xhtml:li>
</xhtml:ol>
<xhtml:p>First try.</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">
        $('iframe form').bind(funtion(){

                submit: function(){             
        
                        console.log('Success!');

                }

        });
</xhtml:pre>
<xhtml:p>Not working.</xhtml:p>
<xhtml:p>A little research on Stackoverflow and I've a similar problem
and a few answers, a quick look on the jQuery's documentation and a
working example at <xhtml:a href="http://api.jquery.com/contents/">http://api.jquery.com/contents/</xhtml:a>.</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">
        $('iframe') .contents().find('form').bind(function(){

                submit: function(){                     

                        console.log('Success!');

                }

        });
</xhtml:pre>
<xhtml:p>It's not working. Instead of DOM element tree I'm getting an
<xhtml:strong>empty jQuery object</xhtml:strong>.</xhtml:p>
<xhtml:p>More reading, more <xhtml:a href="http://stackoverflow.com/questions/1199075/keydown-event-on-a-iframe">
answers</xhtml:a>. Looks similar but I had to give it a try.
Unfortunately it wasn't the solution for my problem either. Still
getting a blank document.</xhtml:p>
<xhtml:p>A snippet from Stackoverflow below:</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">
        $(document.getElementById('IFrameId').contentWindow.document).keydown( 

            function(){

                 alert('Key down!'); 

            }

        );
</xhtml:pre>
<xhtml:p>More and more reading and finally I understood what was the
problem. Document in iframe <xhtml:strong>wasn't ready at the time of
executing the event attach</xhtml:strong>. I found an answer on
Stackoferwlow and made my script based on it:</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">

    var url = 'http://localdomain.com';

    //creating an iframe
    $('.iframewrap').
    append('<xhtml:iframe id="frameid" width="95%" height="90" frameborder="0" scrolling="no" name="frameid"/>');

    //caching jQuery object
    var iframe = $('#frameid');

    //styling and setting url
    iframe.css({'border': 'none', 'overflow': 'hidden'});
    iframe.attr('src', url);

    //making sure iframe's content is ready
    iframe.load(function(){

        callback(this);

    });          
       

    function callback(frame){
       
       //pay attention to the way of creating 
       //selector's context $('#frameid').contents()!

       $('#sendnewsletter', $('#frameid').contents()).bind({
       
             submit: function(){
                    
                    //hiding a page loaded after submission...
                    $('#frameid').fadeOut('slow', function(){
                            
                           //...and showing our gratitude  
                           $('#postsendmsg')
                                .html('Thanks for subscribing!');

                    });
                    
             }
             
       });
       
    }
</xhtml:pre>
<xhtml:p>It cost me a couple of hour but now I'm satisfied with how it
looks and works, and what's the most important I really learned a
lot.</xhtml:p>
<xhtml:p>Recapitulating: if you want to do a cross domain AJAX request
you can:</xhtml:p>
<xhtml:ol>
<xhtml:li>
<xhtml:p>Make a get request and get a JSONP answer.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Make a proxy server side script which will make a request
instead of JavaScript.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>You can use an iframe and manipulate it's structure when you are
sure the hole document is loaded.</xhtml:p>
</xhtml:li>
</xhtml:ol>
<xhtml:p>Of course there is more solutions based on YQL and Flash. I
haven't tested them yet so I'm just giving a sort note about theirs
existence.</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[11 jQuery performance tips]]></title>
    <summary type="html"><![CDATA[Once again I was trying to do a one thing and I've end up with something else. 
    For about month I've wanted to write neat summary of JavaScript tutorial from 
    <a href="http://javascript.info">http://javascript.info</a>. 
Unfortunately I don't have enough time so I have to do something less ambitious.]]></summary>
    <published>2011-08-10T19:56:54+02:00</published>
    <updated>2011-10-30T17:20:16+01:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/11-jquery-performance-tips"/>
    <id>http://blazejklisz.pl/blog/article/11-jquery-performance-tips</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Today I've watched a slides from a great presentation whose
author is <xhtml:a href="http://addyosmani.com">Addy Osmani</xhtml:a>. Slides
can be found here: <xhtml:a href="http://addyosmani.com/jqprovenperformance/">jQuery Proven
Performance Tips And Tricks (Slides)</xhtml:a>. I strongly recommend
watching it (with all linked tests on <xhtml:a href="http://jsperf.com">http://jsperf.com</xhtml:a>) and if necessary read my
short summary posted bellow.</xhtml:p>
<xhtml:ol>
<xhtml:li>
<xhtml:h3 class="main-point">Stay up to date</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>If it's possible try to use the <xhtml:strong>latest version of
jQuery</xhtml:strong>.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>If you're updating library <xhtml:strong>check</xhtml:strong> if all
plug-ins still work, if not - look for a plug-in updates.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>New releases of jQuery can be divided into two groups. If a
second number is changed (1.3 =&gt; 1.4) we can expect a new
features and a performance improvements, also a chance of lack of
compatibility with currently used plug-in is quite high. If a third
number is changed it means we're dealing with a bug fixes so some
problems can be fix and there shouldn't be any problems with a
compatibility. Of course we shouldn't expect any speed
improvements.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Use the fastest selectors</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>The best selectors are those using <xhtml:strong>ID</xhtml:strong>. jQuery
can take an advantage of plain JS method <xhtml:a href="http://javascript.info/tutorial/searching-elements-dom#document-getelementbyid">
getElementById()</xhtml:a>.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Second in a line are <xhtml:strong>element selectors</xhtml:strong> using
native <xhtml:a href="http://javascript.info/tutorial/searching-elements-dom#document-node-getelementsbytagname">
getElementByTagName()</xhtml:a> method.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Selectors based on <xhtml:strong>classes</xhtml:strong> are not so great
even if modern browser have native <xhtml:a href="http://javascript.info/tutorial/searching-elements-dom#document-node-getelementsbyclassname">
getElementsByClassName()</xhtml:a> method.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Pseudo and <xhtml:strong>attribute selectors</xhtml:strong> are the slowest
one. The list of browsers with native <xhtml:a href="http://javascript.info/tutorial/searching-elements-dom#document-node-queryselector-queryselectorall">
querySelector()</xhtml:a> and <xhtml:a href="http://javascript.info/tutorial/searching-elements-dom#document-node-queryselector-queryselectorall">
querySelectorAll()</xhtml:a> methods is shorter then the previous
one.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Choosing the best method for obtaining
children and parents</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>If you want to find a children of a given element you got at
least a few methods to chose from. You can use <xhtml:a href="http://api.jquery.com/jQuery/#jQuery1">context (created or
cached)</xhtml:a>, <xhtml:a href="http://api.jquery.com/children/">children()</xhtml:a> method, <xhtml:a href="http://api.jquery.com/find/">find()</xhtml:a> method or use all kinds of
selectors based on CSS.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>According to Addy Osmani <xhtml:strong>find()</xhtml:strong> method used on
a cached parent element is generally the fastest one. It'll be the
best in most cases but really it depends on situation... so to be
sure, you have to check it anyway. <xhtml:img src="/images/postimages/jquery-performance-tips/selectors-comparation.png" alt="selectors-comparation"/></xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Try to use plain JavaScript</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>For simple task such as retrieving value of ID attribute it's
<xhtml:strong>faster to do it by yourself in pure JS</xhtml:strong> that doing
it in jQuery which will do it in JS anyway spending more time on
it.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Cache elements</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>Traversing through DOM tree can be time-consuming task so it's
better to avoid it. Instead of creating the same element over and
over again <xhtml:strong>try to cache</xhtml:strong> it by assigning it to a JS
variable. Next time you'll be using this element, DOM traversing
will be omitted.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Use method chaining</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>Most of jQuery methods return a jQuery objects. It means that
immediately after one method you can call another method on the
object returned by the first method. Sounds complicated? Please
look at example:</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">
$('div').find('span')
    .addClass('hidden')
    .fadeOut();
</xhtml:pre></xhtml:li>
<xhtml:li>
<xhtml:p>It's clearer way of writing code and it's got a better
performance.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">For mass event creating use delegate()
method</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>It have advantages over bind() and live() methods. The bind()
method doesn't support elements created after the <xhtml:a href="http://api.jquery.com/bind/">bind()</xhtml:a> method was called. For
this type of situations you have to use the <xhtml:a href="http://api.jquery.com/live/">live()</xhtml:a> or the <xhtml:a href="http://api.jquery.com/delegate/">delegate()</xhtml:a> method. The live()
is a simple implementation of delegation used in vanilla JavaScript
(you can read about it here: <xhtml:a href="http://javascript.info/tutorial/event-delegation">Event
delegation</xhtml:a>). It's a great concept helping to avoid cloning
event handlers. So why not the live()? It's slower and it don't
allow for chaining.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Watch out for adding elements to DOM</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>Don't append new elements if you are looking for a place to
store data. Use a <xhtml:a href="http://api.jquery.com/data/">data()</xhtml:a>
method instead.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>When you're append an element try to do it on a cached element.
Beside that do it once with prepared string. Look at this
performance test: <xhtml:a href="http://jsperf.com/string-concat-single-append-vs-multiple-append">http://jsperf.com/string-concat-single-append-vs-multiple-append</xhtml:a></xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Try to use <xhtml:a href="http://api.jquery.com/detach/">detach()</xhtml:a>
method.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Use data() method in these way:</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">
$.data('#elem', key, value)
</xhtml:pre>
rather then this way:
<xhtml:pre class="brush: js; toolbar: false;">
$('#elem').data(key, value)
</xhtml:pre>
.</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Use native loop rather than $.each()</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>It's better to take advantage of selector engine than use loops.
If you have to use a loop try the native one in the first
place.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>A great loops` compression: <xhtml:a href="http://jsperf.com/jquery-each-vs-for-loop/24">http://jsperf.com/jquery-each-vs-for-loop/24</xhtml:a></xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">Avoid creating unnecessary objects</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>This way:</xhtml:p>
<xhtml:pre class="brush: js; toolbar: false;">
$.text($elem)
</xhtml:pre>
is much better than this way:
<xhtml:pre class="brush: js; toolbar: false;">
$elem.text();
</xhtml:pre>
<xhtml:div class="clear"/>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
<xhtml:li>
<xhtml:h3 class="main-point">DRY that is Don't Repeat Yourself</xhtml:h3>
<xhtml:ul>
<xhtml:li>
<xhtml:p>More repeated code means greater size, greater mess and more
problems with maintenance. Looks quite obvious.</xhtml:p>
</xhtml:li>
</xhtml:ul>
</xhtml:li>
</xhtml:ol>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Time-consuming PHP and JavaScript]]></title>
    <summary type="html"><![CDATA[I can't believe that more then 2 months have past since my last post. I'll try to show what I've been doing
when I wasn't writing. In other words how it's happened that I've started with writing o blog about MySQL 
problems and end up learning JavaScript. Reading, learning, studding, searching, programming and... no time 
for writing]]></summary>
    <published>2011-06-25T19:26:43+02:00</published>
    <updated>2011-07-04T21:50:35+02:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/time-consuming-php-and-javascript"/>
    <id>http://blazejklisz.pl/blog/article/time-consuming-php-and-javascript</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>First of all 2 main projects. Learning PHP 5.3, <xhtml:strong>PHP
design patterns</xhtml:strong> and learning <xhtml:strong>plain
JavaScript.</xhtml:strong></xhtml:p>
<xhtml:p>After years of searching a good book about PHP, that could help
me rise my skills into upper level, I've found it. It's <xhtml:a href="http://www.apress.com/9781590599099">PHP Objects, Patterns, and
Practice by Matt Zandstra</xhtml:a>. What's so great about this book?
Almost 200 pages about design patters from the perspective of PHP.
It helped me understand a lot and still helping because I haven't
finished yet. After I've read it once it becomes my textbook during
creating my private projects. Beside design patters, this book have
nice chapters about OOP - nothing fancy, but it may help make some
quick review, PEAR library, phpDocumentator, SVN, PHPUnit, Phing
and Continuous Integration. Cutting a long story short this book is
giving you a great foundations of skills that you need to have if
you like to consider yourself as advanced PHP programmer. As
additional learning resource I recommend series about design
patterns - <xhtml:a href="http://css.dzone.com/books/practical-php-patterns">Practical PHP
patterns</xhtml:a> and new series about refactoring <xhtml:a href="http://css.dzone.com/books/practical-php-refactoring">Practical
PHP refactoring</xhtml:a>.</xhtml:p>
<xhtml:p>Second most time consuming project, came up unexpectedly. After
spending hours and hours on PHP I needed some break, so I decided
to do a small research on things that would be nice to learn. This
way I've "lost" a reading about what is really happening the world
of web applications. I've rediscovered a term <xhtml:acronym title="Rich Internet Application">RIA</xhtml:acronym> and diversity of
frameworks for creating one page applications. As many times before
questions and answers on <xhtml:a href="http://stackoverflow.com">stackoverflow</xhtml:a> helped me to
straighten up issues and give a good starting point. Let me just
name most important tools for creating rich applications. I'll try
back to this topic and do a small review on each of frameworks
listed below, but for now I'll start with something simpler. If you
see any mistakes let me know.</xhtml:p>
<xhtml:p>Rich user interfaces based on the most popular open source
JavaScript frameworks:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://jqueryui.com/">jQuery UI</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://developer.yahoo.com/yui/">YUI Library</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://mochaui.org/">MochaUI</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://dojotoolkit.org/widgets/">Dijit and
DojoX</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>Frameworks based on JavaScript, more complex, tconcentrated only
on RIA</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://www.sencha.com/products/extjs/">Ext JS
4</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://www.bindows.net/">Bindows</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://qooxdoo.org/">qooxdoo</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>More advanced solutions based not strictly on JavaScript:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://cappuccino.org/">Cappuccino</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://www.sproutcore.com/">SproutCore</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>Frameworks giving a foundation for creating applications rather
than a set of widgets:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://www.javascriptmvc.com/">JavaScriptMVC</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://knockoutjs.com/">Knockout JS</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://documentcloud.github.com/backbone/">Backbone</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>Based on JAVA:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://www.zkoss.org/">ZK</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://vaadin.com/">Vaadin</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://www.openfaces.org/">OpenFaces</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://www.smartclient.com/">SmartClient</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://echo.nextapp.com/site/echo3/">Echo3</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>If you're looking for small handy tools for some JS job? Try at
<xhtml:a href="http://microjs.com/">microjs</xhtml:a>.</xhtml:p>
<xhtml:p>When I saw all of this I've realized that my basic skills at
JavaScript are much too low to go further then applications based
on jQuery User Interface which I already know. Then I've found
probably the best on line tutorial ever, it's available at <xhtml:a href="http://javascript.info/">http://javascript.info/</xhtml:a>. After a few
weeks of learning I've not only organized my knowledge about JS,
but also filled knowledge gaps and learned many new thing. What's
interesting from day to day writhing scripts in jQuery became much
easier. My advise - if you know some of JavaScript frameworks, take
a step back and learn at least solid foundations of pure
JavaScript.</xhtml:p>
<xhtml:p>Beside things mentioned before I've started reading <xhtml:a href="http://www.amazon.com/exec/obidos/ASIN/1848000693/thealgorithmrepo">
The Algorithm Design Manual by Steven Skiena</xhtml:a>. Definitly it's an
interesting book, but I'm sure that wading through this book will
take a several months.</xhtml:p>
<xhtml:p>At the end a list of most interesting articles, libraries and
presentations I've read and seen lately: First 3 links lead to Andy
Osmani's works. He really showed me a new level of building
applications using jQuery.</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://addyosmani.com/blog/large-scale-jquery/">Building
Large-Scale jQuery Applications</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://addyosmani.com/blog/building-spas-jquerys-best-friends/">Building
Single Page Applications With jQuery's Best Friends</xhtml:a></xhtml:li>
<xhtml:li><xhtml:a href="http://addyosmani.com/toolsforjqueryapparchitecture/">Tools For
jQuery Application Architecture (Extended Slides)</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>Nice library build on a top of jQuery UI. Partly free, can by
used under MIT or GPL license.</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://wijmo.com/widgets/wijmo-open/">WIJMO</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>If you're looking for a good resource about HTML5 take a look
at:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://diveintohtml5.org/">DIVE INTO HTML5</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>Great collection of JavaScript libraries and jQuery
plug-ins:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://coding.smashingmagazine.com/2011/04/07/useful-javascript-and-jquery-tools-libraries-plugins/">
Useful JavaScript and jQuery Tools, Libraries, Plugins</xhtml:a></xhtml:li>
</xhtml:ul>
<xhtml:p>Last link is a nice presentation of what can be done in a
JavaScript:</xhtml:p>
<xhtml:ul>
<xhtml:li><xhtml:a href="http://www.chromeexperiments.com/detail/gravitational-particle-system-sandbox/">
Gravitational Particle System Sandbox</xhtml:a></xhtml:li>
</xhtml:ul>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Difference between JOIN with WHERE condition and JOIN with subquery with WHERE condition]]></title>
    <summary type="html"><![CDATA[Today I'll say about very useful thing which I've learned lately - a method for filling gaps created by joined tables having no rows meeting some of the conditions or in other words how to change range of WHERE clause and move it from main query to the joined subquery. ]]></summary>
    <published>2011-04-06T21:16:51+02:00</published>
    <updated>2011-04-07T20:22:31+02:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/difference-between-join-and-join-with-subquery"/>
    <id>http://blazejklisz.pl/blog/article/difference-between-join-and-join-with-subquery</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>As example I'll use sakila sample database. Our objective is to
get a list of movies with the number of actors which first or last
name starts with letter a. First lets check how many movies that
meet that condition is there.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT
            count( DISTINCT film_id)
    FROM
        film LEFT JOIN film_actor using (film_id)
        LEFT JOIN actor using (actor_id)
    WHERE
        first_name like 'a%'
        OR last_name LIKE 'a%'
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>Now we know that in 407 films appeared the definite actor. So
now lets list them:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT
            film_id,   title,   count( actor_id )
    FROM
        film LEFT JOIN film_actor using (film_id)
        LEFT JOIN actor using (actor_id)
    WHERE
        first_name like 'a%'
        OR last_name LIKE 'a%'
    GROUP BY
        film_id
    ORDER BY
         1 ASC
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>The result looks like this:</xhtml:p>
<xhtml:img src="/images/postimages/difference-between-join-and-join-with-subquery/select-title-from-film-join-actor.jpg" alt="Result of 3 joined tables with a global condition"/>
<xhtml:p>All right, we got list of all movies that has at least one
specific actor, but what if we want list of all movies with the
number of actors even if the number is 0? We have to modify our
query.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT
            film_id,   title,   IFNULL(count, 0)
    FROM
        film LEFT JOIN ( SELECT
            film_id,
                 count(  actor_id) as count
         FROM
             film_actor LEFT JOIN actor using (actor_id)
        WHERE
            first_name like 'a%' OR   last_name LIKE 'a%'
        GROUP BY
            film_id) as act using (film_id)
    ORDER BY
         1 ASC
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>Now that's more like it:</xhtml:p>
<xhtml:img src="/images/postimages/difference-between-join-and-join-with-subquery/select-title-from-film-join-subquery.jpg" alt="Result of join with subquery and local condition"/> The the
difference is clear but how does it work? Lets split this statement
into two separate queries:
<xhtml:ul>
<xhtml:li>
<xhtml:p>first one is simply a list of films with no conditions</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT
            film_id,   title
    FROM
        film
    ORDER BY
         1 ASC
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>Probably you could imagine the result yourself:</xhtml:p>
<xhtml:img src="/images/postimages/difference-between-join-and-join-with-subquery/select-title-from-film.jpg" alt="Result of SELECT title FROM film"/></xhtml:li>
<xhtml:li>
<xhtml:p>second is quite similar to the query that gave as a result list
of 407 movies with specific actors:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT
            film_id,   count( actor_id ) as count
    FROM
        film_actor LEFT JOIN actor using (actor_id)
    WHERE
        first_name like 'a%'
        OR last_name LIKE 'a%'
    GROUP BY
        film_id
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>Adding a title we could get a result identical to the result of
first query:</xhtml:p>
<xhtml:img src="/images/postimages/difference-between-join-and-join-with-subquery/count-actor-by-film_id.jpg" alt="Result of SELECT film_id, count(actor_id) as count..."/></xhtml:li>
</xhtml:ul>
<xhtml:p>How many rows do we get as a result of this query? Any guess?
Lets check.</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT
            count( distinct film_id)
    FROM
        film_actor LEFT JOIN actor using (actor_id)
    WHERE
        first_name like 'a%'
        OR last_name LIKE 'a%'
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>407 rows. I've to say I was suprised by the result.</xhtml:p>
<xhtml:p>So basically what we are doing in the correct query is a
selecting the list of all film, and than joining to each of those
films (using a film_id column) a number of actors. What if there is
no actors' number? We are using LEFT JOIN, so if it is empty we are
attaching null value. If we were using INNER JOIN we wouldn't get
this row at all. On the image below you can see what will be joined
to each titles.</xhtml:p>
<xhtml:img src="/images/postimages/difference-between-join-and-join-with-subquery/titles-matching-actors-number.jpg" alt="Titles and suiting actor numbers"/>
<xhtml:p>First query was creating a list of titles with actors' number
and that filtering result using WHERE clause, removing all rows
that don't meet the conditions (that is those who had no specific
actors - 0 as a number).</xhtml:p>
<xhtml:p>The most important thing in this axample was a changing a scope
of WHERE condition from "global" - affecting all 3 joined tables
into "local" - filtering only this part of result that will be
later attached into outer query result</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[MySQL EXPLAIN step by step - Part 1]]></title>
    <summary type="html"><![CDATA[If you are looking for a good tool that will help make your query faster or you've already known about it but  you hadn't been able to understand the result you've got, you are in right place. I'll try to clarify how EXPLAIN statement works.]]></summary>
    <published>2011-04-02T17:16:37+02:00</published>
    <updated>2011-04-09T14:12:20+02:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/mysql-explain-step-by-step-part1"/>
    <id>http://blazejklisz.pl/blog/article/mysql-explain-step-by-step-part1</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>All demonstration statements were run on Sakila sample database
which can be downloaded from <xhtml:a href="http://dev.mysql.com/doc/index-other.html">here</xhtml:a>. Lets start
with a first, very simple query:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
SELECT *
FROM `sakila`.`film`;
</xhtml:pre>
<xhtml:p>As a result we get all rows and columns from film table. Now let
see what we get when we precede previous query with a EXPLAIN word.
Query:</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
EXPLAIN SELECT *
FROM `sakila`.`film`;
</xhtml:pre>
<xhtml:p>Result should be similar to this:</xhtml:p>
<xhtml:img src="/images/postimages/mysql-explain-step-by-step-part1/EXPLAIN-SELECT-1.jpg" alt="explain result"/>
<xhtml:p>One row and five non null columns: id, select_type, table, type,
rows. Some of those columns, like id, table, rows, are
self-explanatory (it doesn't mean that they always be, but right
now they are), some look much more cryptic, so lets look closer to
them.</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:strong>id</xhtml:strong> is simply a number that identifies query -
we got one statement so it's marked as 1.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>select_type</xhtml:strong> shows the kind of SELECT we are
dealing with. Basically we can distinguish between simple and
complex statements. At this point this columns doesn't give much
information because it's clear that query was SIMPLE. Other
possible types will be discussed later.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>table</xhtml:strong> we can see that film table was used in
this query. Quite obvious.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>type</xhtml:strong> according to the <xhtml:a href="http://dev.mysql.com/doc/refman/5.0/en/explain-output.html" title="Mysql manual">MySQL manual</xhtml:a> this columns show a join type. You
may find this a bit strange considering lack of any joins and other
tables. We should look at this table wider that a join type. Please
look on the quote below from <xhtml:a href="http://oreilly.com/catalog/9780596101718">High Performance
MySQL.</xhtml:a></xhtml:p>
<xhtml:blockquote>It's more accurate to say the access type - in other
words, how MySQL has decided to find rows in the table.<xhtml:span class="author">High Performance MySQL</xhtml:span>
<xhtml:div class="clear"/>
</xhtml:blockquote>
<xhtml:p>So how MySQL find ALL rows? It have to do a full table scan,
read each row in table. On manual we can find it information that
the ALL value is the worst of all. Why? Because it means a server
has a really much to do, but in query like this, when we want to
find all rows in table there is no other option.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>rows</xhtml:strong> column shows as a value an estimated
number of rows that server must read to find what we want. It's
quite interesting that this number can be wrong, it's just an
estimation made by MySQL. Actually film table has a 1000
rows...</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Lets make a brief summary what information we get from EXPLAIN
statement: we know that we made a one simple SELECT and that to get
the result MySQL had to read 953 rows from film table. Pretty nice
for a few additional letters before source statement.</xhtml:p>
<xhtml:p>OK, lets try something more complex. A query that gives as a
result list of all films starting with letter "f".</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
EXPLAIN SELECT *
FROM `sakila`.`film`
WHERE title LIKE 'f%'
</xhtml:pre>
<xhtml:div class="clear"/>
<xhtml:p>If everything went all right you should see something like on
screen below.</xhtml:p>
<xhtml:img src="/images/postimages/mysql-explain-step-by-step-part1/explain-select-with-index.jpg" alt="explain result"/>
<xhtml:p>Probably you've already notices that this time there is only a
one null column. Lets look at rest of them:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p><xhtml:strong>id</xhtml:strong> - just like a a last time, number
identifying our query.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>select_type</xhtml:strong> - again we have a SIMPLE
SELECT.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>table</xhtml:strong> - once again, we are selecting rows from
film table.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>type</xhtml:strong> - at last some new values - a range access
type. What does it mean? Explaining our first query we get an ALL
for a access type because there wasn't any conditions. This time we
were looking for titles starting with letter f - a subset of table.
It makes a perfect sense, doesn't it? (actually it's more
complicated, but lets assume at this point that it's clear).</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>possible_keys</xhtml:strong> - in this column we can find a
list of indexes which could be helpful during a query execution.
MySQL shows that idx_title is a possible key and if we do a</xhtml:p>
<xhtml:pre class="brush: sql; toolbar: false;">
 SHOW INDEX FROM  film
    
</xhtml:pre>
query we'll get to know that on title column there is really a
index called idx_title.</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>key</xhtml:strong> - this column shows which of indexes was
chosen to execute query as most efficient as possible. We've got
only one candidate for this role and it was chosen. Certainly there
are also other scenarios but at this point let stick by our
example.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>key_len</xhtml:strong> - a maximum length of key that could
possibly used in query. I wrote "possibly used", not "used",
because EXPLAIN statement doesn't measure values in rows, it simply
looks only at table definition.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>rows</xhtml:strong> - 46 rows had to be red to serve the
result.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p><xhtml:strong>Extra</xhtml:strong> - it's an additional information about
query execution. Looking at out query "Using where" shouldn't be
surprise in this place, but honestly I've to admit why there is
"Using where" instead of "Using index".Using where mean that result
was filtered just before sending it to the client. Why at the stage
of reading records? Defenitly have to read more about it. If you
have any clues please leave comment below.</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>Now it's time for a second summary. We've made one simple select
statement from film table, which returned 46 rows, which used
idx_title (that was only possible key and whose maximum length is
767) and range table access.</xhtml:p>
<xhtml:p>So first EXPLAINs behind us. In next part I'll try to show and
tell about a few more values that could appear when you're working
just on a single table.</xhtml:p>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[<?php echo Hello World]]></title>
    <summary type="html"><![CDATA[A short introduction to subjects I'm going to write about and some organizational things. Non original title and non original blog post, but I've to start somehow.]]></summary>
    <published>2011-03-28T18:58:38+02:00</published>
    <updated>2011-04-07T20:31:59+02:00</updated>
    <link rel="alternate" type="text/html" href="http://blazejklisz.pl/blog/article/php-echo-hello-world"/>
    <id>http://blazejklisz.pl/blog/article/php-echo-hello-world</id>
    <author>
      <name>Blazej Klisz</name>
      <email>the_joshua_tree@o2.pl</email>
      <uri>http://blazejklisz.pl</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>First of all, this site is not done already. I've still got a
lot to do, a bunch o ideas that will be implemented with the
passing of time and beside that I've quite a few things to learn. I
count on feedback from you on topics I could write about, on things
that could be done better, on lacks of functionalities of the site
and exceptionally on any mistakes I've made, and anything I don't
understand correctly. I've tested this site under FireFox 4 and
Chrome 10, any older versions won't be supported. Cutting a long
story short - send e-mails (using contact form) and write comments
below articles.</xhtml:p>
<xhtml:p>As you already are on my site and probably it's not a
coincidence (taking into consideration poor positioning on google)
you are really determined to find some information about web
programming. I hope you find what you're looking for and your next
visit here will be more intentional.</xhtml:p>
</xhtml:div>
    </content>
  </entry>
</feed>
