Quick Answer: Add Random Dates to MySQL Database

January 30, 2008

Looking for a way to add random dates to a column in one of your MySQL tables?

I ran across this problem and found a straightforward solution. By utilizing str_to_date(), concat(), floor() and rand() you can specify a random date for a column.

update  mytable
set     mycolumn = str_to_date(
                               concat(
                                      floor(1 + rand() * (12-1)), 	/* Generate a random month */
                                      '-',
                                      floor(1 + rand() * (28 -1)), 	/* Generate a random day */
                                      '-',
                                      '2008'
                                      ),
                                '%m-%d-%Y'
                                );

Creating VIEWs in MySQL

January 3, 2008

The MySQL VIEW acts like a virtual table. Each VIEW is actually a SQL statement that has been previously defined.

To create a VIEW:

CREATE VIEW view_name AS
sql_statement;

A basic VIEW could be created as the following:

CREATE VIEW Cities AS
SELECT     DISTINCT(City)
FROM       Customers
ORDER BY   City ASC;

When we run a SHOW COLUMNS FROM Cities MySQL returns the following:

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| city  | varchar(50) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.16 sec)

To access the information from the newly created VIEW:

SELECT     City
FROM       Cities
LIMIT      5;

And MySQL returns:

+----------------+
| city           |
+----------------+
| 100 MILE HOUSE |
| ABBOTSFORD     |
| ABBOTT PARK    |
| ACHESON        |
| ACTON          |
+----------------+
5 rows in set (0.09 sec)

I know this example is incredibly simple, but I hope you can see the potential for using VIEWs. The creation syntax for VIEWs also includes the capability to assign an algorithm type (either AUTO, MERGE or TEMPTABLE) and there are some limitations (not being able to access user variables). The example that I have included is the most simplified method for creating a new view.

With the MySQL VIEWs I am able to simplify other-wise complicated SQL statements. To generate summary level details (by using several aggregate functions) and JOIN that information to more readable SQL, I am saving myself a lot of debugging and troubleshooting if future modifications are required.

For example if I was working on a bulletin board application and I want to display a summary for a user:

CREATE VIEW user_summary AS
SELECT     Users.UserID,
           COUNT(Comments) AS user_comment_count,
           COUNT(Posts) AS user_post_count
FROM       Users LEFT JOIN
           (
            Comments LEFT JOIN Posts
            ON
             (
              Comments.PostID = Posts.ID
             )
            )
            ON
             (
              Users.UserID = Comments.UserID
             )
GROUP BY   Users.UserID;

Now I have a VIEW that contains the bulletin board summary information for the users. To JOIN the VIEW to another SQL statment:

SELECT    Users.UserID,
          user_summary.user_comment_count,
          user_summary.user_post_count
FROM      Users LEFT JOIN user_summary
          ON
           (
            Users.UserID = user_summary.UserID
           );

If you have any questions, or would like further clarification. Please leave me a comment and I will answer you promptly.


Quick Answers: Dynamically Apply a Border to all IMGs in the DOM

January 2, 2008

Many people have asked me to put up a Quick Answer that would allow them to dynamically apply a border to all IMG elements in the DOM.

Before …

border-002.png

After …

border-001.png

To dynamically apply CSS padding and borders to all IMG elements in the DOM, you can use the following Javascript function:

<html>
  <head>
    <script language="Javascript">
      function drawIMGBorder()
      {
        //Create a reference of all IMG elements in DOM
        var imgs = document.getElementsByTagName('img');

        //Loop through each of the IMG elements
        for(i = 0; i <= (imgs.length -1); i++)
        {
          //Apply CSS padding to current IMG
          imgs[i].style.padding = "2px";
          //Apply CSS border to current IMG
          imgs[i].style.border = "2px Solid #cacaca";
        }
      }
    </script>
  </head>
<body onLoad="drawIMGBorder();">
  <img src="picture1.jpg" border="0" />
  <img src="picture2.jpg" border="0" />
</body>
</html>

In this example the Javascript function is called when the page loads, but this can easily be modified to another Javascript event.


Join Tables Across Different Databases

January 2, 2008

Joining tables in queries across different MySQL databases is possible if you use fully qualified database and table names.

Both databases will need to be on the same server for this to work 😉

SELECT  db1.table1.column1,
        db2.table1.column1
FROM    db1.table1 LEFT JOIN db2.table1
        ON
          (
            db1.table1.column2 = db2.table1.column2
          );

The example query will pull two columns (column1 from both databases) and display the results of the LEFT JOIN.


Introduction to Regular Expressions in MySQL

January 2, 2008

Using the LIKE clause can only get you so far when you are building search functionality into your applications. Implementing Regular Expressions will open your search functionality far beyond the most complicated LIKE statement you can create.

SELECT    City
FROM      Customers
WHERE     City REGEXP 'vancouver'
ORDER BY  City ASC;
SELECT    City
FROM      Customers
WHERE     City REGEXP '.ancouver'
ORDER BY  City ASC;

The “.” is used to replace a single character in your search string.

The querys above would work the same if you replaced REGEXP with LIKE (and used wildcards). The main difference between LIKE and REGEXP is that LIKE matches entire column values (unless wildcards are used), and REGEXP automatically searches for matches within the column values.

SELECT     City
FROM       Customers
WHERE      City REGEXP "Vancouver|Richmond"
ORDER BY   City ASC;

Searching for multiple items can be accomplished by separating the searches with the OR operator (|).

SELECT     City
FROM       Customers
WHERE      City REGEXP '[St|Saint] Johns'
ORDER BY   City ASC;

[] is used to specify AND as a operator, [12345] and [1|2|3|4|5] are the same.

It is important to note that ‘St|Saint Johns’ and ‘[St|Saint] Johns’ will not produce identical results. Below are the example queries and their respective output:

SELECT    Distinct(City)
FROM      Customers
WHERE     City REGEXP '[st|saint] john';
+--------------+
| City         |
+--------------+
| ST JOHN'S    |
| SAINT JOHN   |
| FORT ST JOHN |
+--------------+
3 rows in set (0.09 sec)
SELECT     City
FROM       Customers
WHERE      City REGEXP 'st|saint john';
+-----------------------------+
| City                        |
+-----------------------------+
| ESTEVAN                     |
| FORESTBURG                  |
| ST-ISIDORE                  |
| ESTERHAZY                   |
| EAST YORK                   |
...
| ALVINSTON                   |
| EAST PROVIDENCE             |
+-----------------------------+
148 rows in set (0.14 sec)

The ‘st|saint john’ query is requesting all cities that include the letters ‘st’ OR ‘saint john’, whereas the ‘[st|saint] john’ query requested the letters ‘st john’ AND ‘saint john’. Big difference!

[1-9] is shorthand for [123456789]

[a-e] is shorthand for [abcde]

If you are still with me on the REGEXP syntax, my next post will go further into searching for multiple instances and repetition in MySQL.


									

Quick Answers: How many images are in the DOM?

January 2, 2008

You can dynamically determine the number of images (<img>) on a web page by using Javascript.

var imgCount = document.getElementsByTagName('img').length

To create a reusable function you can use the following code:

function countAllImages()
{
var imgCount = document.getElementsByTagName('img').length;
return imgCount;
}

Forms Without Tables

January 2, 2008

Tableless Form 001Tables are overused in web development these days. I must admit that years ago (around 1995) I used tables to help position elements in web pages. NEVER USE TABLES to format your forms. Not only are tables tacky but they will require more time to modify layouts and do not make much sense in terms of accessibility.

CSS (Cascading Style Sheets) allows you to define the formatting and layout of your web pages. Using CSS will add greater flexibility to your web sites and reduce the time it would take to adjust layout changes versus HTML.

I am going to start building the table less form in a <div>:

<div id="form_body">
  <form method="post" action="">
    <fieldset>
      <legend>Shipping Details</legend>
      <ul>
        <li>
          <label for="name">Attention<em>*</em></label>
          <input type="text" name="name" id="name" />
        </li>
        <li>
          <label for="street_address">Street Address<em>*</em></label>
          <input type="text" name="street_address" id="street_address" />
        </li>
        <li>
          <label for="city">City<em>*</em></label>
          <input type="text" name="city" id="city" />
        </li>
        <li>
          <label for="province">Province<em>*</em></label>
          <input type="text" name="province" id="province" />
        </li>
        <li>
          <label for="postal_code">Postal Code<em>*</em></label>
          <input type="text" name="postal_code" id="postal_code" />
        </li>
        <li>
          <label for="email">Email</label>
          <input type="text" name="email" id="email" />
        </li>
        <li>
          <label for="submit"> </label>
          <input type="submit" name="submit" id="submit" value="Continue" class="button" />
      </ul>
    </fieldset>
  </form>
</div>

Without any CSS Rules being applied, we now have a form that looks like the following:

Forms Without Tables 002
To prevent your visitors from running away from the horribly formatted form, I am going to start applying CSS.

I will first specify the font to be used:

#form_body
{
  font: 8pt Arial;
}

Next I will specify the <fieldset> border, background color and of course the <legend> style:

#form_body fieldset
{
  border: 1px Solid #c8c8c8;
  background: #f0f0f0;
  width: 300px;
}
  #form_body fieldset legend
  {
    font: Bold 8pt Arial;
  }

Now we can apply some formatting to the <ul> and the child <li> elements:

#form_body fieldset ul
{
  margin: 0;
  padding: 0;
}
  #form_body fieldset ul li
  {
    list-style: none;
    margin-bottom: 3px;
    text-align: left;
  }

Here is the CSS to position the <label> for each of the <input> items, this is where all the magic happens:

#form_body fieldset ul li label
{
  width: 150px;
  float: left;
}
  #form_body fieldset ul li label em
  {
    color: #ff1515;
    font: 10pt Arial;

  }

Before I display the final bit of CSS, let’s take a look at our HTML now:

Forms Without Tables 003

Now all that is needed is to specify the formatting of the <input> elements:

#form_body fieldset ul li input
{
  border: 1px Solid #c8c8c8;
  font: 8pt Arial;
  width: 150px;
}
#form_body fieldset ul li input.button
{
  border: 1px Solid #71ff72;
  background: #caffca;
  font: 8pt Arial;
}

Before I display some other possible enhancements to the form here is the entire HTML to reproduce our new table less form:

<html>
<head>
  <style type="text/css">
    #form_body
    {
      font: 8pt Arial;
    }
      #form_body fieldset
      {
        border: 1px Solid #c8c8c8;
        background: #f0f0f0;
        width: 300px;
      }
        #form_body fieldset legend
        {
          font: Bold 8pt Arial;
        }
        #form_body fieldset ul
        {
          margin: 0;
          padding: 0;
        }
          #form_body fieldset ul li
          {
            list-style: none;
            margin-bottom: 3px;
            text-align: left;
          }
            #form_body fieldset ul li label
            {
              width: 150px;
              float: left;
            }
              #form_body fieldset ul li label em
              {
                color: #ff1515;
                font: 10pt Arial;

              }
            #form_body fieldset ul li input
            {
              border: 1px Solid #c8c8c8;
              font: 8pt Arial;
              width: 150px;
            }
            #form_body fieldset ul li input.button
            {
              border: 1px Solid #71ff72;
              background: #caffca;
              font: 8pt Arial;
            }
  </style>
</head>
<body>
  <div id="form_body">
    <form method="post" action="">
      <fieldset>
        <legend>Shipping Details</legend>
        <ul>
          <li>
            <label for="name">Attention<em>*</em></label>
            <input type="text" name="name" id="name" />
          </li>
          <li>
            <label for="street_address">Street Address<em>*</em></label>
            <input type="text" name="street_address" id="street_address" />
          </li>
          <li>
            <label for="city">City<em>*</em></label>
            <input type="text" name="city" id="city" />
          </li>
          <li>
            <label for="province">Province<em>*</em></label>
            <input type="text" name="province" id="province" />
          </li>
          <li>
            <label for="postal_code">Postal Code<em>*</em></label>
            <input type="text" name="postal_code" id="postal_code" />
          </li>
          <li>
            <label for="email">Email</label>
            <input type="text" name="email" id="email" />
          </li>
          <li>
            <label for="submit"> </label>
            <input type="submit" name="submit" id="submit" value="Continue" class="button" />
        </ul>
      </fieldset>
    </form>
  </div>
</body>
</html>

To add a more modern look, we can change the background properties of the <fieldset>. Below are some examples with gradient backgrounds:

forms-004.pngforms-005.png

Applying a background image to the <fieldset> is very straight forward:

#form_body fieldset
{
  border: 1px Solid #c8c8c8;
  background: url('green_grad.jpg') repeat-x top left;
  width: 300px;
}