Showing posts with label HTML 5. Show all posts
Showing posts with label HTML 5. Show all posts

Saturday, June 5, 2010

RGrid for PHP: Datagrid class for PHP & MySQL


RGrid for PHP: Datagrid class for PHP & MySQL


Introduction

This is a PHP datagrid class which can show the MySQL result set which you pass to it as a paged list. It can be completely styled using CSS (which looking at the examples, I'm sure you'll be grateful for). A quick example:

/**
    * Include the RGrid code
    */
    require_once('RGrid.php');
    
    $params['hostname'] = 'localhost';
    $params['username'] = 'root';
    $params['password'] = '[PASSWORD]';
    $params['database'] = 'phpguru';

    $sql = "SELECT cm_id,
                   ne_title,
                   cm_author,
                   cm_datetime,
                   cm_status,
                   cm_neid
              FROM comments,
                   news
             WHERE cm_status = 'ACTIVE'
               AND cm_neid = ne_id
          ORDER BY cm_id DESC";

    /**
    * Create the datagrid with the connection parameters and SQL query
    * defined above. You MUST specify an ORDER BY
    * clause (with ASC/DESC direction indicator) - if not then ordering
    * will be disabled.
    */
    $grid = RGrid::Create($params, $sql);
    
    $grid->Display();
?>
This will show a bare bones list of comments from this website. You will probably want to customise this quite a bit (appearance wise), which you can do with CSS, and with the various methods available to you (eg.SetDisplayNames()).

Features

  • Order by any of the columns in both ascending and descending directions
  • Tailored to MySQL
  • Allows any HTML in the columns (eg. Pictures)
  • Easily change the look and feel by using CSS
  • Friendly column names
  • Alternative column or row color for easy reading
  • Customisable mouse over highlight
  • You can hide columns
  • Automatic record paging (defaults to 25 records per page)
  • Fully supports all browsers: Internet Explorer, Firefox, Chrome, Safari and Opera
  • Handles large database recordsets.

Examples

Below is an IFRAME showing one of the example scripts which you can get from the download area. Bear in mind that the example scripts look more complicated than would be typical as they show off everything (or try to) and the HTML and CSS are in the same file as the PHP.

Example 1 :: Example 2 :: Example 3 :: Example 4 :: Example 5 :: Example 6 :: Example 7 :: Example 8Example 9 


Customisation

You can customise the "look and feel" using CSS. The grid uses a single table, which has the class datagrid. The headers are inside a tag, and the paging correspondingly in a tag. Using CSS you can then create corresponding CSS rules for them:

.datagrid thead th {
    background-color: #ddd;
    border-top: 2px solid #bbb;
    padding-left: 5px;
    text-align: left;
}
Naturally the body of the table uses a along with cells.

Structure

The tag structure of the datagrid is explained by this picture. Consider it "nice" structure, as it should be. The table has a class attribute of datagrid, the headers are in cells, which themselves are in a tag. The body rows are in cells, and a tag. And the footer is in a tag.
Doing it this way allows finer grained control over the style. eg: .datagrid thead th is the CSS selector that you would use to change the style of the headers.

Method reference

What follows is a list of public methods and what they do. You will probably be able to guess from their names though. They're in no particular order.

Static methods

  • RGrid::CreateFromArray($array)
    Returns an RGrid object created using the (associative) array that you pass to it (called statically).
  • RGrid::Create($connection[, $sql])
    Returns an RGrid object based on the parameters that you pass to it. $connection can either be a MySQL connection and the second an SQL query which provides the desired results. Or $connection can be an (associative) array (and the second argument omitted) to create a datagrid based on that.

Regular methods

  • Constructor (eg $grid = new RGrid($connection[, $resultset]))
    Creates a new RGrid object. You should pass it your MySQL connection ($connection) and the result set that was returned from your call to mysql_query(). The result set is what the datagrid will show. If you want an array based datagrid then you can pass an array as the first argument and no second argument. There's no real difference between using the second method versus the static shortcut methods above. 
  • $grid->SetDisplayNames($names)
    This function sets the display names of the columns. You should pass it an associative array of column names (the actual column name as the index, and the desired name as the value). See the example scripts for an example. 
  • $grid->HideColumn('column', ...)
    Specifies the given column names (actual names) as hidden - ie not displayed. Give one or more column names. 
  • $grid->NoSpecialChars('column', ...)
    Specifies that the given column names will not have htmlspecialchars() applied to them. You need to use this if you want to have HTML in your column. 
  • $grid->NoSort('column', ...)
    Specifies the given column names cannot be sorted (ie they're not linked). Give the function one or more column names. 
  • $grid->GetPageCount()
    Returns the number of pages in the dataset. 
  • $grid->GetRowCount()
    Returns the number of rows in the result set. 
  • $grid->GetResultset()
    Returns the underlying MySQL result set. 
  • $grid->GetConnection()
    Returns the under lying MySQL connection. 
  • $grid->SetHeaderHTML($html)
    Sets the header HTML that is displayed above the actual datagrid. This is not related to the column headers - it is displayed above the actual datagrid. 
  • $grid->SetConnection($connection)
    Sets the MySQL connection. Not that you should need to, but here it is. 
  • $grid->SetPerPage($num)
    Sets the amount of rows that are displayed per page. 
  • $grid->SetResultset($resultset)
    Sets the MySQL result set that is used to make the datagrid. 
  • $grid->AddCallback($function)
    This is what you can use to customise the datagrid. The argument is the name of a function that is called for every row in the datagrid. The function is passed the row as the only argument. Specify the argument to be passed by reference. Like this:




    $grid->AddCallback('RowCallback');
    
    function RowCallback(&$row)
    {
        if ($row['status'] == 'PASS') {
            $row['status'] = 'PASS';
        } else {
            $row['status'] = 'FAIL';
        }
    }

  • $grid->Display()
    Shows the datagrid. If you want it assigned to a variable, then you can use output buffering (ob_start() etc). 


HTML5 CANVAS introduction


A mini HTML5 canvas tutorial if you like

Introduction

A line graph created using RGraph
(FF3.5+, Chrome 2+, Safari 4+, Opera 10.5+, Internet Explorer 8)
he new HTML5 CANVAS tag is a new tag for HTML5 that allows 2-dimensional drawing, or bitmap drawing if you like, using Javascript. It allows both simple and complex shapes to be drawn that you could previously only get by using images. It's what my RGraph graphing library is based on.

Browser support

The CANVAS tag is part of HTML5, and as such only supported by some browsers. Most of them, but not all. They are:

  • Mozilla Firefox
  • Google Chrome
  • Apple Safari
  • Opera
You should note that Mozilla Firefox, Google Chrome and Apple Safari all support the canvas text and shadow APIs, however Opera doesn't (not even Opera 10 as of 20th August 2009).
Because Microsoft Internet Explorer doesn't yet support it, it's not really feasible to use it for mainstream use. The canvas tag is in the HTML5 specification though, so it's just a matter of time. For internal use, such as admin areas or intranets, where you can stipulate the browser, it will be fine.
Note 

Regarding RGraph - as of January 2010, Microsoft Internet Explorer 8 is supported in conjunction with ExCanvas, and Opera 10.5 has support for the canvas text and shadow APIs.

Example

The graph to the top-right is produced using the CANVAS based RGraph - my HTML5 graphing library. This is an example of how you can use the new tag to produce things that you could previously only use images or plugins for. You will notice that it's quite fast. Subsequent page views will be even faster because the library will be cached, and you will only have to download a few hundred bytes of data.

How to use the canvas tag

The new tag is very easy to use, and boils down to two steps:

  1. Define the tag
  2. Script it
For example:


    [Content that is shown to users using browsers that don't support the canvas tag]
This is just a small example. There's another, working, example here. Or alternatively, just look at my graphing software - RGraph, which is based around the canvas element.
Using it isn't hard. First you get a reference to the HTML tag in the usual way usingdocument.getElementById(), then get a reference to the context (there's only one at the moment - 2d. After you've done that you can manipulate it using the properties and methods made available to you via the context object. If you want a reference to what's available to you, consult the HTML5 specification. But suffice to say there are methods and properties for controlling colour, drawing lines, drawing arcs.
Unsurprisingly for a new API, there's discord when it comes to text. The HTML5 specification does account for text, but at the time of writing no browser implemented these. Fortunately whilst writing the RGraphlibrary I used the CanvasText.js code, and adapted it. Eventually this will not be needed as browsers eventually support native text drawing.
Update

More recent browsers, (eg Firefox 3.5, Chrome 2 and Safari 4) support the canvas native text drawing APIs.

The 2D context API

This is not complete by any means, listing the most commonly used methods and properties. If you want a complete reference I suggest you consult the W3C HTML5 specification.

  • moveTo(x, y)
    Moves the "pen" to the given x/y coordinates
  • lineTo(x, y)
    Draws a line from the current position to the given x/y coordinates.
  • strokeRect(x, y, width, height)
    Draws a rectangle, but does not fill it.
  • fillRect(x, y, width, height)
    Draws a rectangle and fills it.
  • beginPath()
    Begins a new path, with an empty set of sub-paths
  • closePath()
    Marks the current sub-path as closed and creates a new subpath
  • save()
    Saves the current pixel state on to the state stack. If for example you call save(), translate, draw something, and then call restore(), the co-ordinate system will be as it was.
  • restore()
    Resets the co-ordinate system to as it was when you called save() last. If you haven't, then this method will do nothing.
  • arc(x, y, radius, startAngle, endAngle, anticlockwise)
    Perhaps unsurprisingly, this method draws an arc. If you haven't yet stroke()ed, then you will get a line from the last point of what you've drawn to the start of the arc.
  • fill()
    Fills what you're drawing with the current fillStyle setting.
  • stroke()
    Strokes what you're currently drawing.
  • lineWidth
    I'm sure you can guess. it's a property that controls how thick the lines are drawn.
  • lineCap
    A proprty that controls how the ends of lines are drawn. Not really a big deal if your lines are thin, but it's noticeable when lines are thicker.
  • lineJoin
    Determines how browsers will draw the join of two lines. ie Round or square. 
  • scale(x, y)
    Scales the canvas (ie the x/y coordinates)
  • rotate(a)
    Rotates the canvas. A common gotcha is that the angle that you give should be measured in RADIANS. 1 radian is equal to 57.296 degrees.
  • translate(x, y)
    Moves the coordinate system by the given x and y amounts. So if you translate by 10 pixels in the X direction and 10 pixels in the Y direction, 0,0 will bedrawn in the same place as 10,10 would have before the translation.
  • transform(m11, m12, m21, m22, dx, dy)
    The transform() method is used for matrix operations.
  • setTransform(m11, m12, m21, m22, dx, dy)
    The setTransform() method is used for matrix operations.

Possible uses

The obvious use is graphing, but you could also use it for a multitude of other things, like games or animation (using the Javascript setTimeout() function). You could quite easily use it to implement your own !

HTML 5

Introduction

HTML4 has been with us for a while now, roughly ten years. And it hasn't really seen a major update. Sure there's XHTML, but that did little more than make things slightly stricter - making you write better quality code if you were at all concerned with compliance. HTML5 does more than that. For one thing it adds a few new features. Not a huge amount, but the ones that it does add are very useful.
Work on HTML5 started way back in 2004, and now it's starting to get interesting. Browser support is increasing, and the element I'm most interested in - CANVAS - is supported by four out of the major five browsers.

So what's new?

  •  < canvas>< canvas> is a 2D (at the moment - other dimensions may be forthcoming) drawing area controlled by Javascript. You can use it for a wide variety of things - graphs, games, presentations etc. Because it's controlled by Javascript you can interact with it very easily. An example is the tooltips feature I've added to RGraph. In short, click on a bar and you get a tooltip that can contain a wide variety of HTML - images videos etc. I've written a short primer to the < canvas> tag here.
  •  < video>The < video> tag makes it easier to embed video clips into your web pages. It has attributes like src(naturally), autoplay and loop. The < video> tag has implications on usability (eg blind access), and so can contain additional markup describing the video. Ideally, the full transcript of the video.
  •  < audio>The < audio> tag is much like the < video>, but for audio files. Surprisingly.
  •  Context menusHTML5 provides a method of defining context menus, making it easier to use these in web applications. Perhaps not so useful for websites, but certainly for applications where context menus could provide a raft of options without taking up space in the UI.
  •  New structural elementsSince HTML is largely unstructured, a few new elements have been provided to try and rectify this. These elements include:
    • < section> -A section, or section of a chapter of text, or a book.
    • < header> - The page header. This is not the same as the < head> element.
    • < footer> - The footer of the page. Typically where all the legal crapola goes.
    • < nav> - Navigation links to other pages. You could put your websites navigation in this for example.
    • < article> - A blog article could be encapsulated by this for example.
    • < aside> - The aside tag can be used to provide extra information for a block of text. Much like sidebar material in books etc
    • < figure> - The < figure> element can be used to annotate your main text with diagrams, which aren't necessarily imperative to the text.
  •  New inline elementsHTML5 introduces new elements to help indicate basic elements such as times or numbers.
    • < mark> - This denotes that a bit of text is marked in some way. You could for example, use this to mark search terms in a list of results.
    • < time> - You can use this to represent times, or dates in your block of text.
    • < meter> - This can be used to indicate a figure of some sort. It can have multiple attributes including: value, min, max, low, high and optimum.
    • < progress> - This can be used to show a progress bar of some sort. It has a couple of attributes:value and max. The max attribute can be omitted.
  •  New form input typesThe input element can now have a new set of types, including:
    • datetime
    • datetime-local
    • date
    • month
    • week
    • time
    • number
    • range
    • email
    • url
    Some of these are already common in desktop UIs, so shouldn't be difficult to implement, and will be more familiar to users when filling out your form.
  •  Dropped elementsThe folling elements have been dropped or replaced:
    • acronym
    • applet
    • basefont
    • big
    • center
    • dir
    • font
    • frame
    • frameset
    • isindex
    • noframes
    • noscript
    • s
    • strike
    • tt
    • u
  •  Character encoding syntaxThe character encoding syntax for a HTML5 document is now: < meta charset="UTF-8">
  •  New interactive elementsSome nice things that will make building websites and, perhaps more pointedly, web applications, easier.
    • < details> - This can be used to provide further information about something specific. For example it could be implemented by browsers as tooltips. This tag can have an open attribute which dictates whether the content is initially shown to the user or not.
    • < datagrid> - Unlike traditional tables (which are designed to be static), this can be used to provide a set of data with some degree of interactivity. For example selecting rows or columns, editing data, sorting and generally interacting with the data in the client.
    • < menu> - Previously a deprecated element, is back in HTML5 with a new meaning. It can, for example, contain elements which cause a particular action to happen. For example you could use this element to provide a toolbar of sorts, or a context menu (see above). It can have label and icon attributes. They can be nested to provide multiple levels of menus.
  •  New DTDHTML5 has a new, much simpler DTD: < !doctype html> Much nicer I think you'll agree and far more memorable. As I understand it, this results from HTML not being associated with SGML any more.
  •  Optional href on linksThis is now optional as links can be used in conjunction with scripting. Perhaps more useful in web applications as opposed to web sites.
  •  The async attributeThis stipulates that a block of script can be executed asynchronously, instead of blocking the rest of the page until it's finished.

Summary

HTML5 could well be the update to HTML that everyone has been waiting for. It provides useful additions to the language that will make building web based applications far more easily and efficiently, at the same time as making the code simpler.
Naturally not all browsers will support everything (< cough>MSIE), but it will come in time, and new items have been specifically designed to accomodate this. So everyone wins. Most browsers already support some of the specification, some for a long time. An example of this is < canvas>, supported by Firefox, Opera, Chrome and Safari. AFAIK Firefox 3.1 will support more of it, namely the < audio> and/or the < video> tags. Can't wait.

Related links