Languages and Tools


One of the great promises that actually came true when our Internet-enabled world reached the twenty-first century is efficient customer-to-business interaction. Each day, I find a new way to go through life’s errands without ever waiting on hold for a bank teller, a pharmacist, or an insurance agent. I do it all online.

Internet savvy consumers are coming to expect such web empowerment. And while these information transactions usually require some sort of private data traveling the ether, you, as the webmaster, bear the burden of keeping that data away from those who have no right to it.

Since retina scans and brain wave signatures are still properties of James Bond flicks, we’re stuck using plain old boring passwords.

Is this really secure?

Let’s get this out of the way first. The only truly secure computer is one that’s unplugged. Kind of like “the only safe car is the one that sits in your garage.” Life is a risk/reward proposition and, let’s face it, this (probably) isn’t Fort Knox, we’re securing.

The security measures listed here are suitable for garden-variety data. I’ve used these schemes to write back-end website administration pages for online shopping carts. I’ve used them to write “partner” pages where retailers can download ads and sales data from wholesalers. I wouldn’t use them to secure credit card numbers, social security numbers, or nuclear launch codes.

So what are PHP, MySQL, and session variables?

PHP is a programming language used (in this case) to write HTML. MySQL is a database. Session variable are used by web servers to track information from one page on a domain to another. This article isn’t a how-to for either technology. If you aren’t very comfortable with them, you could just copy and paste the code samples in this article and build yourself a basic password protected website. You could also just read the Cliff’s notes for Pride and Prejudice and get a C+ in literature class. Your choice.

Let’s get started with sessions

It’s often been said that the web is “stateless”, meaning that each web page is entirely independent, needing no other page to exist, and taking no information from the previous page. This is great for anonymous surfing from one site to the next, but it stinks for password protection. Consumers want password protected information, but they don’t want to enter their password on every page. So we turn to our web server to keep track of a user while he’s on our site.

Ex. 1.

<?php

session_start();

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

</body>

</html>

end Ex. 1

session_start() is a PHP function that looks to see if a session has already been started then does one of two things:

1. If a session has been started, it does nothing.

2. If a session has not been started, it begins one.

It is important to note that session_start() must occur before any other PHP on the page, if you want it to work. Begin every password-protected page with it. Validation

Now let’s think basic validation. What sorts of things do we need to accomplish?

* First, we need to check to see if the user has already logged in, so we don’t ask for a password on every page. If our user has already logged in, we pass him or her through to the secure content.

* If the user hasn’t already logged in, we need him or her to do so. So we need to write a log-in form.

* We need next to compare log-in form results with a known list of usernames and passwords. If the user checks out, we pass him or her along to the secure content.

* If the user doesn’t check out, we direct him or her back to the log-in screen.

* Lastly, we need to provide the user the ability to log out.

So let’s start with a basic frame-work that we’ll fill in later.

Ex. 2

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

// if yes, return true

// if no, check to see if visitor has just tried to log on

// if yes, verify password

// if it worked, return true

// if it didn’t, send them back to log-in

// if the user didn’t just log-in, (s)he needs to

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 2

As I said, this is just a frame-work. I like to start all my projects this way. It allows me to get a grand view of what I’m doing before getting mired down in the details.

Basically, so far, all we’ve done is place some secret content inside an if statement. If the user is valid, we show the content, if not, we don’t. Writing a log-in form

The first thing we should flesh out is our log-in function. This is a basic form, with no bells and whistles, so it should be pretty straight forward.

Ex 3

function write_log_in( $text )

{

echo ”

<p>$text</p>

<form method=’post’ action=”>

<p>User ID: <input type=’text’ name=’user_name /></p>

<p>Password: <input type=’password’ name=’password’ /></p>

<p><input type=’submit’ value=’Log In’></p>

</form>

“;

} // end write_log_in function

End Ex. 3

No problems, right? All this is is PHP writing a basic HTML log-in form. Two things are worth noting:

1. The method attribute to the <form> tag is ‘post’. We could have used ‘get’, but that would add our user name and password to the URL as varibles. ie our_url?user_name=bob&password=truck64 . This shows the password–in plain text– right there in the URL. Why spend all this time on security if you’re just going to put peoples’ passwords out for display?

‘post’ is much more secure, forcing the server to keep track of form data, rather that the URL. Any time you can keep information out of the URL, you’re one step closer to a secure web page.

2. Next you want to look at the action attribute to the <form> tag. Leaving it blank tells the server that you plan to process these form results with this same page.

Checking the log-in values

Now let’s flesh out our frame-work a little more.

Ex. 4

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

// if yes, return true

// check to see if visitor has just tried to log on

$user_name = $_POST["user_name"];

$password = $_POST["password"];

if ( $user_name && $password )

{

// verify password and log in to database

$db = mysql_pconnect( “localhost”, “$user_name”, “$password” );

if ( $db )

{

// register session variable and exit the verify function

$valid_user = $user_name;

$_SESSION['valid_user'] = $valid_user;

return true;

}

else

{

// bad user and password

$text = “User Name and Password did not match”;

write_log_in( $text );

}

}

else

{

// if the user didn’t just log-in, (s)he needs to

}

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 4

First, we’ll check whether the user has just tried to log in.

$_POST is a PHP superglobal array that keeps track of data sent to a page via a <form method=’post’> tag. In the log-in function, we named our inputs user_name and password, so we can access the user input by calling $_POST["user_name"] and $_POST["password"].

We next run an if ( $user_name && $password ) statement to see if both $_POST["user_name"] and $_POST["password"] hold values. If they do, the user just tried to log in.

Our next section of code is the part that actually checks whether the user name and password are correct. Here, we use MySQL’s User table (part of the mysql database) to keep track of our users. This is, perhaps, the best route, as MySQL is already set up to control access permissions. However, this can present problems when you want to keep the database connection open across pages. Also, some hosting companies won’t give you grant access (let you make new users) to the mysql database.

In those cases, you can accomplish much the same thing by setting up your own users table in your database. You would then need to write an SQL query that compares user names and passwords. That would look something like this:

Ex. 5

$select = “select user_name from users

where user_name=’$user_name’

and password=PASSWORD( ‘$password’ )”;

$query = mysql_query( $select );

if ( mysql_num_rows( $query ) == 1 )

{

// validated user and password

End Ex 5

Getting back to our validation using MySQL’s built in features, we know that the user name and password checked out because the connection attempt returned true.

Registering a session variable

Now that we know our user name and password check out, we need to store that information and allow our user to continue surfing our protected area without logging in each and every page. Looking back at example four, we notice another of PHP’s superglobal variables: $_SESSION.

$_SESSION is an array that holds all of our session variables. By setting the valid_user session variable, we can later make a call to ession_is_registered( “valid_user” ) to see if our user has already logged in successfully.

Logging out

The last thing we have to attend to is allowing our users to log out of our system. In this case, we’ve used a simple link inside our protected area.

Ex 6

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

session_unregister( “valid_user” );

session_destroy();

session_start();

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

echo “<p><a href=’?log_out=1′>Log out</a></p>”;

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

End Ex 6

First, looking in the HTML body, we see a simple HTML link that adds a variable to the URL. In this case, the variable name is log_out and its value is 1. We use 1 as a value because it’s easy to store in a URL, but really any value greater than zero will work.

Once we pass a log-out request to the page, we need to process it. That’s what the if( $log_out) part is for.

The if statement checks if a log-out request was passed. Once it sees that one was, it unregisters the valid_user session variable, then it destroys the session entirely.

Ironically, it starts a new session right back up. That’s in case the user decides to log in later (without closing the browser window), or log in as a different user. The final code

Putting it all together we get this:

Ex. 7

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

session_unregister( “valid_user” );

session_destroy();

session_start();

}

function write_log_in( $text )

{

echo ”

<p>$text</p>

<form method=’post’ action=”>

<p>User ID: <input type=’text’ name=’user_name /></p>

<p>Password: <input type=’password’ name=’password’ /></p>

<p><input type=’submit’ value=’Log In’></p>

</form>

“;

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

if ( session_is_registered( “valid_user” ) ) return true;

// check to see if visitor has just tried to log on

$user_name = $_POST["user_name"];

$password = $_POST["password"];

if ( $user_name && $password )

{

// verify password and log in to database

$db = mysql_pconnect( “localhost”, “$user_name”, “$password” );

if ( $db )

{

// register session variable and exit the verify function

$valid_user = $user_name;

$_SESSION['valid_user'] = $valid_user;

return true;

}

else

{

// bad user and password

$text = “User Name and Password did not match”;

write_log_in( $text );

}

}

else

{

// user must log in

$text = “This is a secure server. Please log in.”;

write_log_in( $text );

}

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

echo “<p><a href=’?log_out=1′>Log out</a></p>”;

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 7

That’s a pretty hefty code block to put at the head of every web page. Typically, I would put my verify() and write_log_in()functions into a seperate file and reference them with an include() function. That provides the added benifit of updating your entire website by editing one file only.

Hope that helps.

Copyright (C) 2005 Dan McConkey

About The Author

Dan McConkey is a freelance web marketing professional, working in and around Charlotte, NC. In the web, Dan has found an amazing potential for lead generation for businesses. Using traditional advertising theories, appropriate technologies, and a little common sense, your electronic marketing campaigns can easily be your most effective.

Dan maintains Dan McConkey’s Free Web Marketing Guide at http://www.dmcconkey.com

dmcconkey@yahoo.com

When it comes to designing a Website, there are several modern programming techniques that can make the designer’s task much easier. Once the content and focus of the Website is decided, layout should become the focus of development. What fonts will be used for the various links and text? Which color will be used to make certain links more prominent than others? Most importantly, how will the designer ensure the entire Website has an isometric appearance? If used properly, CSS can accomplish those tasks, while reducing bandwidth and increasing page-load timeframes.

WHAT IS CSS AND HOW CAN IT BE USED?

CSS is an abbreviation for Cascading Style Sheet. It can consist of several lines of text to control content appearance within a Webpage, or multiple pages within a Website. There are two common ways that a Style Sheet can be used. First, it can be added to the, “head,” of each individual Webpage. A more efficient way to implement a Style Sheet, is to up-load the file into a Directory on a Website, and utilize an include tag.

Posting the style sheet within the head of each page will increase the amount of bandwidth used and slightly affect the download speed of pages. This is dependent on the size of a particular site and the number of styles included on the CSS. If a change-of-style is decided upon in the future, each individual Webpage will require editing, to affect the entire Website. For example, if a designer wished to apply a holiday theme around Christmas, he or she would need to edit the CSS on every page for the change to take affect.

In contrast, a CSS file can be uploaded onto a Host. Once uploaded, a designer can use a simple include tag, to call upon the style sheet. This method-of-use can reduce the amount of bandwidth used and increase speed times, as some visitors will have the CSS stored on their computers following the first page load. Additionally, it will make style changes much easier as only one file needs to be changes to affect all relevant pages within a given Website.

DEVELOPING A STYLE SHEET

Open any text editor with a blank page. Save the page as, something.css”. If it was decided to upload the file for use, this will be the actual file uploaded. Additionally, a designer can copy and paste from this file, if it is to be included within the head of each Webpage.

Before beginning to add actual tags, consider how links should apppear and the various sections of the Website or Webpages. If a Style Sheet becomes sloppy, it will make the designer’s job difficult. Therefore, start simple and keep the CSS clean. The Style Sheet should begin with simple grouping. For example, all pages may be utilizing an identical header and left menu. If the text styles are going to be different, this could be are first two simple groups, along with link formats.

MANAGING HYPERLINKS WITH CSS

With our first two groups we can add five lines to the style sheet. These are (alphabetized) A:LINK, A:HOVER, A:VISITED, .head, and .leftmenu. With these five lines, we can control the appearance of links, visited links, mouse-overs on links, the header of all pages, and the left menu.

Now we are going to add some basic variations to the text. After, A:LINK and A:VISITED,” add a space then, “{color: #004080}”. Notice that no font attributes have been added. This is because we are going to utilize different fonts within the other tags. The only thing being changed on linked text is the color. Change the color to reflect the desired appearance. Note, this can be adjusted to personal preference.

ADDING THE HEADER AND MENU TEXT TO THE STYLE SHEET

Once the desired link colors are decided, the font attributes can be associated to the header and left menu. After the .head and .leftmenu, add a space then, “{font-family: Arial, Helvetica, sans-serif; font-size: 11pt; font-weight: normal; text-transform: capitalize;}”. To explain, we are specifying any area of text with the .head style will use one font (font-family), be a uniform size (font-size), have a uniform weight (font-weight), and regardless of typing be transformed to capitals (text-transform). A modified version should be added to the left menu.

Here is how the CSS should currently appear:

A:link {color: #004080}
A:visited {color: #004080}
A:hover{color:ff3300}
.head “{font-family: Arial, Helvetica, sans-serif; font-size: 11pt;
font-weight: normal; text-transform: capitalize;}
.leftmenu “{font-family: Arial, Helvetica, sans-serif; font-size: 11pt; font-weight: normal; text-transform: capitalize;}

IMPLEMENTING THE STYLE SHEET

If it was decided to past the style sheet onto each page, add:

<STYLE TYPE=”text/css”><!—
A:link {color: #004080}
A:visited {color: #004080}
A:hover{color:ff3300}
.head {font-family: Arial, Helvetica, sans-serif; font-size: 11pt;
font-weight: normal; text-transform: capitalize;}
.leftmenu {font-family: Arial, Helvetica, sans-serif; font-size: 11pt;
font-weight: normal; text-transform: capitalize;}
–></STYLE>

- to each page of the site that will utilize the Style Sheet. The style sheet should be placed between the <head> and </head> tags of the document.

If it was decided to upload the sheet and call upon the file on each page, add, “<LINK href=”http://links.mjmls.com/ name of the file” type=text/css rel=stylesheet>”. Once again, this should be placed between the <head> and </head> tags. Change the link location to where the style sheet is located on the Web Host.

CALLING THE STYLE SHEET ON WEBPAGES

There are a variety of ways to call upon the different text attributes. This depends widely on site layout. If the site is designed using tables, we can simply specify the style for each cell, rather than each word. For example, the table code could appear as:

<table width=”100%”>
<tr>
<td CLASS=”HEAD”><a href=”http://links.mjmls.com”>Home</a></td>
<td CLASS=”HEAD”>Next link</td> etc…
</tr>
</table>

As a stand-alone link, within the given Webpage, we can add the class tag to the Hyperlink:

<a href=”http://links.mjmls.com” class=”head”>Home</a>

To modify an entire group of stand-alone text, the CSS tag could be added to the paragraph tag:

<p class=”head”>The entire paragraph of text is affected</p>

It could be suggested that calling the style tags are experimented with, prior to modifying an entire Website. By adding class=”head” or class=”leftmenu” to various tags, a new designer will learn how the style tags can work, reduce the size of a Webpage, save bandwidth, and provide a uniform appearance throughout a Website.

In part two, we will demonstrate some other attributes that could be added to different tags and applying CSS to tables.

About The Author

Michael J Medeiros is the owner and founder of www.mjmls.com

Mjmls provides various advertising venues for businesses and individuals including a new Website Directory http://links.mjmls.com  

There is nothing wrong with making your own website if you are looking to save some money. Be prepared however, for your finished product to resemble an after school project; cutesy, homemade touches and all. It is pretty hard to make your own website and have it look professional; but, there is an easier way that will leave you with fewer headaches in the long run.

You must first do some web research. Click around and find websites that have the look you are going for. Make some notes and jot down what it is you do and do not want representing you. You should also start thinking of some keywords that will help people find you if they were to type them into a search engine.

After you have a rough idea of what you would like your site to look like, you should contact a professional who will take care of all the hassles that come with making a webpage. I recommend contacting Global Presence in Tucson, Arizona, http://www.saeler.com; they do great work and pay special attention to detail.

Your website will be created so that you can make changes when and if you see fit. To do this, you should purchase a web authoring program, and learn how to properly navigate the system to make revisions on your site. After the site is up, you only need to know how to do 4 things in order to keep your site up to date.

1. Be able to add a new page, complete with all of the navigation buttons from previous pages.

2. Have the ability to add text.

3. Be able to add a graphic.

4. Know how to make a hyperlink.

These are 4 easy steps that will be repeated numerous times throughout your website’s existence.

Not everyone uses the same browser, so your webpage may look very different from one computer to the next. To get a quick look at how your site may appear on other browsers, go to http://www.anybrowser.com/. When choosing a font, use something standard like Times New Roman; one that virtually every computer has. A good resource to help guide you through all of your website problems is Robin Williams’ (no, not that Robin Williams) book, The Non Designers Web Book.

*Remember to keep your site simple, so that customers don’t get confused by all the buttons, and click away.

About The Author

Tom Antion provides entertaining speeches and educational seminars. He is the ultimate entrepreneur, having owned many businesses BEFORE graduating college. Tom is the author of the best selling presentation skills book “Wake ‘em Up Business Presentations” and “Click: The Ultimate Guide to Electronic Marketing.” It is important to Tom that his knowledge be not only absorbed, but enjoyed. This is why he delivers his speeches laced with great humor and hysterical jokes. Tom has addressed more than 87 different industries and is thoroughly committed to his client’s needs. http://www.antion.com.

The most popular method to build webpages today is to use WYSIWYG (What You See Is What You Get) software. Microsoft FrontPage and Macromedia Dreamweaver are prime examples of WYSIWYG software. Both programs allow you to create webpages as though you were creating a document with your favourite word processing software like Microsoft Word or WordPerfect. Its as simple as entering paragraphs, headings and inserting clipart or images.

WYSIWYG software like those listed above are prefect for beginner webpage builders who want webpages constructed quickly without having to learn HTML (Hyper Text Markup Language).

All webpages are brought to life using HTML codes, regardless what webpage building software is used. WYSIWYG programs simply create the HTML codes as you construct a webpage (in the background, without you knowing), so you don’t need to understand them.

This is without a doubt the biggest advantage over any other type of webpage building programs. It means that if you can press keys on a keyboard, you have what is required to create your very own webpage!

However, most WYSIWYG programs don’t give you absolute, total control over webpage design (ie, exactly the way you want the page to look). There are design limitations.

For example, you may want to place headings, sub headings and a navigation menu in a particular arrangement on the webpage, but no matter how many times you try, the program won’t permit such placement or position them correctly. This is one big disadvantage of WYSIWYG programs if you desire a custom look to all your webpages.

Knowledge of HTML, however, can assist you to overcome such design shortfalls in WYSIWYG programs. How is this possible? Let me explain.

If you understand HTML codes, then you understand why webpages appear the way they do in a web browser, such as Microsoft Internet Explorer or Mozilla Firefox. This is powerful stuff because the moment you change/modify HTML codes, the webpage will take on a new design/appearance.

And don’t forget that HTML codes are exact, giving you total freedom over how everything appears on the webpage. Most WYSIWYG programs allow you to view and modify the HTML codes. As you can see, knowledge of HTML is beneficial.

The downside to HTML is the learning curve. It takes time to understand how HTML works and why, but once you know, using HTML to create totally custom designed webpages is easy. For the beginner, HTML can be challenging, but don’t despair because there are HTML tutorials available that teach you basic and advanced HTML in a matter of days!

So the question is – Should you bother learning HTML to build webpages? The answer – yes and no.

It is obvious that WYSIWYG software speeds up production of webpage development regardless of your knowledge on how to build webpages. However, to further refine and tune your webpages exactly to your liking, it is usually necessary to add and modify HTML codes. So yes, HTML is worthwhile learning if you are unsatisfied with the webpages produced by WYSIWYG software.

There is little point learning HTML if you are 100% satisfied with the webpages made with WYSIWYG software.

One thing is certain. Using WYSIWYG software and learning HTML codes is the answer for those of us who want webpages made exactly to our requirements. Learning HTML is not as hard as you think. To get started, simply search any major search engine like Google, Yahoo or MSN using the search phrase “html tutorials”, its that easy!

About The Author

Les Pinczi is the creator of interactive HTML learning software to assist you in learning how to create a web page in hours! http://www.webpage-teacher.com.

Many of site owners still don’t realize all advantages of database driven web sites and don’t use all abilities they give. So when do you need a database driven web site and how it will make your web-life better?

What is a database driven web site?

Database driven web site is one that uses database for collecting and storing information. What information it can be? Various. Email addresses, contact info, clients list, products list, listings of real estate property, trade offers, images, and links, etc.

How does it work?

For example, you have a static HTML web site for your business with posted information about the company, products or services, clients, and there is contact form.

If you have strong HTML skills you update your site without problems each time you need it. Otherwise you hire a webmaster or use maintenance services of a web design company. You write info in text document, send it to your webmaster, he manually inserts it to the site.

You store your products, clients, and contacts info in Word or Excel files.

Probably you store emails that you receive from contact form in Word or Excel files. Is it handful and easy? Is there an alternative?

In the database driven web site all information is stored in table format of databases on the server, script generates pages that are showed on the site as usual HTML ones.

Usually database driven web sites have admin panel with user-friendly interface where you can manage the site content, i.e. add, edit, or delete info by yourself, create new pages or delete old ones. You can update your site easily each time you need it.

Requests sent form contact form can be saved in database for further use, you can edit them, group, and sort.

You can create pictures gallery on your site and update it easily.

You can have news box at your site and update it easily each time you need it.

Is it expensive?

No, if you order the site from a web design/development company that has good experience in database driven web sites design that means elaborated and tested development process, time and cost saving methods which give high-quality work within short timeline and at affordable price.

Ask your web design company do they make database driven web sites, if yes, look at the examples of such previous works, ask references of the customers – are they satisfied with their web sites? – and if the price is acceptable move forward to your new web site. Or search for another web development company using the same criteria for choice.

What else you should know?

Probably, you will need to change hosting plan or even hosting provider to host your new database driven web site. Usually there are such requirements for hosing:

· Must support PHP/MySQL or ASP/MSSQL
· At least 75-100 Mb of disk space
· Must have Database Client
· Must have Mail server

About The Author

Julia Ramyalg
Marketing Director of IT-Inventors – professional offshore web site design and development company
http://www.it-inventors.com

Visit our site to order Affordable database driven web site design – clients database, online gallery, online albums, news, newsletters, products and services listings, and more.

Prices start from $50

julia@it-inventors.com

1.Never use embedded T-SQL; always use stored procedures.

2.       Never do a select * even if you need all fields from a table or view. This makes code more efficient, reusable and is much less likely that a change may affect an application as it may change the order of the columns etc. The column set should be kept as short as possible.

 

3.       Always obtain execution plan to find table scans or inefficient queries.

 

4.       Don’t return rows that you don’t need. Use the WHERE clause, SELECT TOP or use SET ROWCOUNT X. In SQL 7.0 always use SELECT TOP instead or ROWCOUNT. In SQL 6.5 when setting ROWCOUNT always set it to 0 again after the query.

 

5.       Before executing queries check whether the required values have been passed.

 

6.        Avoid using wildcard (LIKE %) text searches, specially with % at the beginning.

 

7.        Don’t use “ = NULL”, use “IS NULL”.

 

8.       Always add a header with details like a description, author, date, modifications, etc.

 

9.       Use in-line comments when possible. This will make it easier for someone else to understand the queries.

 

10.    Avoid all use of cursors.

 

11.    If possible avoid negative predicates (use of NOT) which always cause a table or index scan.

 

12.    Use the IN keyword in your WHERE clause to specify several conditionals instead of using several OR statements. For example, use this:

WHERE cCustomerState IN (‘CT’, ‘NY’, ‘NJ’)

Instead of this:

WHERE cCustomerState = ‘CT’ OR cCustomerState = ‘NY’ OR cCustomerState = ‘NJ’

 

13.    If you have a trigger on a table that is likely to be bulk changed, do include all code in the trigger rather than calling a stored procedure from it. This will perform better than recurrently calling the SP for each changed record.

 

 

 

 

Further reading:

 

-          Transact-SQL SQL Server Performance Tuning Tips.

http://www.sql-server-performance.com/transact_sql.asp.

 

 

< ?xml:namespace prefix ="" o ns ="" "urn:schemas-microsoft-com:office:office" />

When using the FOR XML clause in your Transact-SQL applications, don’t include the XMLDATA option. The XMLDATA option returns additional XML schema data that generally is not needed. Because of this, using this option adds extra overhead to your server and network connection, reducing performance. [2000] Added < ?xml:namespace prefix ="" st1 ns ="" "urn:schemas-microsoft-com:office:smarttags" />11-16-2000

 

*****

 

The OPENXML function in SQL Server 2000 can be useful for processing multiple table inserts within a single database call, reducing overhead and boosting performance. The ability to map an XML document to a rowset representation of a specified portion of the XML document within a stored procedure can maximize the efficiency with which repetitive type inserts are accomplished. [2000] See related article Added 12-27-2000

 

*****

As you may know, it can be a performance drag on SQL Server and your web server if you SELECT the same data over and over from SQL Server in order to dynamically create web pages. For example, say that you need to display some text on your webpage that is stored in SQL Server, but that it only changes every couple of days. Currently, you are running a SELECT statement from a stored procedure to retrieve the text each time the page is dynamically created and displayed. This can significantly hurt performance, especially if you are getting many page views a second.

One way to help avoid this problem, and to boost SQL Server and your web server’s performance, is to use SQL Server and XML to periodically re-create static content (such as once an hour, once a day, etc.) instead of dynamically pulling the content each time it is needed from SQL Server, and storing this static content on the web server. This assumes, of course, that the data doesn’t change often, as in our example. This method still allows the page to be created dynamically, but when the text is needed to be inserted into the page, it is retrieved locally off the web server, not from SQL Server each time it is needed, reducing overhead and boosting performance. Click here to see an article on how to do this. [2000] Added 1-5-2001

 

*****

SQL Server 2000 offers three types of FOR XML queries. They include RAW, AUTO, and EXPLICIT. Each has performance pros and cons.

The RAW type offers the best overall performance, especially if you will be moving a lot of data. The disadvantage of this is that not all XML-based applications is able to use the format the RAW type returns.

The AUTO type offers the next best overall performance, and many more XML-based applications are able to use the format returned, unless of course your application requires XML data in a predefined format.

If your application has to accept data in a predefined format, then you have to use the EXPLICIT type, which is generally the slowest performing option. [2000] Added 5-9-2002

 

*****

If you need to use the EXPLICIT type of FOR XML query, in some cases you can boost performance if you replace the EXPLICIT FOR XML query with an XPath query instead. XPath queries are faster, and in most, but not all cases, can replace the functionality of a EXPLICIT FOR XML query. [2000] Added 5-9-2002

 

*****

If you have installed SQLXML 2.0 on your SQL Server 2000 server, you can take advantage of a new feature that can significantly affect SQL Server’s performance. SQLXML 2.0 supports what is called the Client Side for XML. What this feature does is to move the conversion from the SQL rowsets to XML at the client, or middle-tier, instead of on the SQL Server. This can significantly reduce the load on SQL Server, helping to boost its performance. Of course, the conversion still has to be done somewhere, and resources on the client or middle-tier must be used to do this. This performance-enhancing feature is especially useful to those whose SQL Server is already operating at full capacity and the workload need to be off-loaded to other servers. [2000] Added 5-9-2002

 

*****

SQLXML 2.0 offers three options to use XML documents to modify a SQL Server database. They include OPENXML, Updategrams, and Bulk Load. Each of these have their own performance-related pros and cons.

As you might guess, the best performance is offered by using Bulk Loads, assuming that it will work for you. If you need to insert very large numbers of XML documents as defined by a mapping schema, then Bulk Loads can be very efficient. But in many instances you can’t use the Bulk Load option because it is only limited to INSERTs, not other types of data modifications.

The next most efficient way to use XML documents to modify a SQL Server database is to use the Updategrams option. Updategrams are more efficient that OPENXML because all XML parsing and SQL statement generation is not performed by SQL Server, but in the client or middle-tier. Like Bulk Loads, Updategrams can’t be used in all instances. Updategrams usually require a mapping schema and also require that XML input be in a special format, which may or may not be practical.

The least efficient, but most flexible way to modify SQL Server data using XML documents, is to use OPENXML. The performance problem is a result that an OPENXML stored procedure is parsed into a DOM by a parser that runs in the SQL Server process, and uses SQL Server memory until it is released. While OPENXML works OK for low-volume applications, it does not scale well. [2000] Added 5-9-2002

 

*****

Here are some ways you can help to maximize the performance of Updategrams:

If you use the sql:key-fields annotation, be sure you select a primary key for each table. If you don’t, all columns in the before element are included in the WHERE clause, and can cause the search to take much longer than necessary.

If you are going to update or delete data a record, and you don’t care what the before value is, you can help boost performance of Updategrams by not including all the columns included in the before element in the WHERE clause.

If an Updategram is used to make unrelated updates, the updates should be split into separate synch blocks. This reduces the transaction size, and helps to boost performance.

[2000] Added 5-9-2002

 

*****

The “Advanced” tab of the “Configure SQLXML Support in IIS” configuration dialog box has a check box to turn “caching” on and off. When on (the default option), allows Mapping Schemas to be cached and used over and over, helping to boost overall performance. Don’t turn this option off, unless you are in a development or testing environment. [2000] Added 5-9-2002

 

 

 

Further reading:

 

-          Transact-SQL SQL Server Performance Tuning Tips.

http://www.sql-server-performance.com/transact_sql.asp.

-          Retrieving Dynamic XML from SQL Server 7.0 and 2000

http://www.15seconds.com/issue/001102.htm

 

Best Practices, and Programming Guidelines

< ?xml:namespace prefix ="" o ns ="" "urn:schemas-microsoft-com:office:office" /> 

Databases are the heart and soul of many enterprise applications, and it is very essential to pay special attention to database programming. I’ve seen in many occasions where database programming is overlooked, thinking that it’s something easy that be done by anyone. This is wrong.

For a better performing database you need a real DBA and a specialist database programmer, let it be for Microsoft SQL Server, Oracle, Sybase, DB2 or whatever! If you don’t use database specialists during your development cycle, databases often end up becoming the performance bottleneck. I decided to write this article in order to put together some of the database programming best practices so that my fellow DBAs and database developers can benefit!

Here are some programming guidelines and best practices, keeping quality, performance and maintainability in mind. This list many not be complete at this moment, and will be constantly updated. BTW, special thanks to Tibor Karaszi (SQL Server MVP) and Linda (lindawie) for taking time to read this article and providing suggestions.

  • Decide upon a database naming convention, standardize it across your organization, and be consistent in following it. It helps make your code more readable and understandable.
  • Make sure you normalize your data at least to the 3rd normal form. At the same time, do not compromise on query performance. A little bit of denormalization helps queries perform faster.
  • Write comments in your stored procedures, triggers and SQL batches generously, whenever something is not very obvious. This helps other programmers understand your code clearly. Don’t worry about the length of the comments, as it won’t impact the performance.
  • Do not use SELECT * in your queries. Always write the required column names after the SELECT statement, like:

SELECT CustomerID, CustomerFirstName, City

This technique results in reduced disk I/O and better performance.

  • Try to avoid server side cursors as much as possible. Always stick to a ‘set-based approach’ instead of a ‘procedural approach’ for accessing and manipulating data. Cursors can often be avoided by using SELECT statements instead.

If a cursor is unavoidable, use a WHILE loop instead. I have personally tested and concluded that a WHILE loop is always faster than a cursor. But for a WHILE loop to replace a cursor you need a column (primary key or unique key) to identify each row uniquely. I personally believe every table must have a primary or unique key.

  • Avoid the creation of temporary tables while processing data as much as possible, as creating a temporary table means more disk I/O. Consider using advanced SQL, views, SQL Server 2000 table variable, or derived tables, instead of temporary tables.
  • Try to avoid wildcard characters at the beginning of a word while searching using the LIKE keyword, as that results in an index scan, which defeats the purpose of an index. The following statement results in an index scan, while the second statement results in an index seek:

    SELECT LocationID FROM Locations WHERE Specialities LIKE ‘%pples’
    SELECT LocationID FROM Locations WHERE Specialities LIKE ‘A%s’

    Also avoid searching using not equals operators (<> and NOT) as they result in table and index scans.

  • Use ‘Derived tables’ wherever possible, as they perform better. Consider the following query to find the second highest salary from the Employees table:

    SELECT MIN(Salary) 
    FROM Employees 
    WHERE EmpID IN
    (
    SELECT TOP 2 EmpID 
    FROM Employees 
    ORDER BY Salary Desc
    )

    The same query can be re-written using a derived table, as shown below, and it performs twice as fast as the above query:

SELECT MIN(Salary) 
FROM 
(
SELECT TOP 2 Salary 
FROM Employees 
ORDER BY Salary DESC
) AS A

This is just an example, and your results might differ in different scenarios depending on the database design, indexes, volume of data, etc. So, test all the possible ways a query could be written and go with the most efficient one.

  • While designing your database, design it keeping “performance” in mind. You can’t really tune performance later, when your database is in production, as it involves rebuilding tables and indexes, re-writing queries, etc. Use the graphical execution plan in Query Analyzer or SHOWPLAN_TEXT or SHOWPLAN_ALL commands to analyse your queries. Make sure your queries do an “Index seek” instead of an “Index scan” or a “Table scan.” A table scan or an index scan is a very bad thing and should be avoided where possible. Choose the right indexes on the right columns.
  • Prefix the table names with the owner’s name, as this improves readability and avoids any unnecessary confusion. Microsoft SQL Server Books Online even states that qualifying table names with owner names helps in execution plan reuse, further boosting performance.
  • Use SET NOCOUNT ON at the beginning of your SQL batches, stored procedures and triggers in production environments, as this suppresses messages like ‘(1 row(s) affected)’ after executing INSERT, UPDATE, DELETE and SELECT statements. This improves the performance of stored procedures by reducing network traffic.
  • Use the more readable < ?xml:namespace prefix ="" st1 ns ="" "urn:schemas-microsoft-com:office:smarttags" />ANSI-Standard Join clauses instead of the old style joins. With ANSI joins, the WHERE clause is used only for filtering data. Where as with older style joins, the WHERE clause handles both the join condition and filtering data. The first of the following two queries shows the old style join, while the second one shows the new ANSI join syntax:

    SELECT a.au_id, t.title 
    FROM titles t, authors a, titleauthor ta
    WHERE 
    a.au_id = ta.au_id AND
    ta.title_id = t.title_id AND 
    t.title LIKE ‘%Computer%’

    SELECT a.au_id, t.title
    FROM authors a 
    INNER JOIN
    titleauthor ta 
    ON 
    a.au_id = ta.au_id
    INNER JOIN
    titles t
    ON
    ta.title_id = t.title_id
    WHERE t.title LIKE ‘%Computer%’

  • Do not prefix your stored procedure names with “sp_”. The prefix sp_ is reserved for system stored procedure that ship with SQL Server. Whenever SQL Server encounters a procedure name starting with sp_, it first tries to locate the procedure in the master database, then it looks for any qualifiers (database, owner) provided, then it tries dbo as the owner. So you can really save time in locating the stored procedure by avoiding the “sp_” prefix.
  • Views are generally used to show specific data to specific users based on their interest. Views are also used to restrict access to the base tables by granting permission only on views. Yet another significant use of views is that they simplify your queries. Incorporate your frequently required, complicated joins and calculations into a view so that you don’t have to repeat those joins/calculations in all your queries. Instead, just select from the view.
  • Use User Defined Datatypes if a particular column repeats in a lot of your tables, so that the datatype of that column is consistent across all your tables.
  • Do not let your front-end applications query/manipulate the data directly using SELECT or INSERT/UPDATE/DELETE statements. Instead, create stored procedures, and let your applications access these stored procedures. This keeps the data access clean and consistent across all the modules of your application, and at the same time centralizing the business logic within the database.
  • Try not to use TEXT or NTEXT datatypes for storing large textual data. The TEXT datatype has some inherent problems associated with it. For example, you cannot directly write or update text data using the INSERT or UPDATE statements. Instead,  you have to use special statements like READTEXT, WRITETEXT and UPDATETEXT. There are also a lot of bugs associated with replicating tables containing text columns. So, if you don’t have to store more than 8KB of text, use CHAR(8000) or VARCHAR(8000) datatypes instead.
  • If you have a choice, do not store binary or image files (Binary Large Objects or BLOBs) inside the database. Instead, store the path to the binary or image file in the database and use that as a pointer to the actual binary file stored elsewhere on a server. Retrieving and manipulating these large binary files is better performed outside the database, and after all, a database is not meant for storing files.
  • Use the CHAR data type for a column only when the column is non-nullable. If a CHAR column is nullable, it is treated as a fixed length column in SQL Server 7.0+. So, a CHAR(100), when NULL, will eat up 100 bytes, resulting in space wastage. So, use VARCHAR(100) in this situation. Of course, variable length columns do have a very little processing overhead over fixed length columns. Carefully choose between CHAR and VARCHAR depending up on the length of the data you are going to store.
  • Avoid dynamic SQL statements as much as possible. Dynamic SQL tends to be slower than static SQL, as SQL Server must generate an execution plan every time at runtime. IF and CASE statements come in handy to avoid dynamic SQL. Another major disadvantage of using dynamic SQL is that it requires users to have direct access permissions on all accessed objects, like tables and views. Generally, users are given access to the stored procedures which reference the tables, but not directly on the tables. In this case, dynamic SQL will not work. Consider the following scenario where a user named ‘dSQLuser’ is added to the pubs database and is granted access to a procedure named ‘dSQLproc’, but not on any other tables in the pubs database. The procedure dSQLproc executes a direct SELECT on titles table and that works. The second statement runs the same SELECT on titles table, using dynamic SQL and it fails with the following error:

    Server: Msg 229, Level 14, State 5, Line 1
    SE
    LECT permission denied on object ‘titles’, database ‘pubs’, owner ‘dbo’.

    To reproduce the above problem, use the following commands:

    sp_addlogin ‘dSQLuser’
    GO
    sp_defaultdb ‘dSQLuser’, ‘pubs’
    USE pubs
    GO
    sp_adduser ‘dSQLUser’, ‘dSQLUser’
    GO
    CREATE PROC dSQLProc
    AS
    BEGIN
    SELECT * FROM titles WHERE title_id = ‘BU1032′ –This works
    DECLARE @str CHAR(100)
    SET @str = ‘SELECT * FROM titles WHERE title_id = ”BU1032”’
    EXEC (@str) –This fails
    END
    GO
    GRANT EXEC ON dSQLProc TO dSQLuser
    GO

    Now login to the pubs database using the login dSQLuser and execute the procedure dSQLproc to see the problem.

  • Consider the following drawbacks before using the IDENTITY property for generating primary keys. IDENTITY is very much SQL Server specific, and you will have problems porting your database application to some other RDBMS. IDENTITY columns have other inherent problems. For example, IDENTITY columns can run out of numbers at some point, depending on the data type selected; numbers can’t be reused automatically, after deleting rows; and replication and IDENTITY columns don’t always get along well.

So, come up with an algorithm to generate a primary key in the front-end or from within the inserting stored procedure. There still could be issues with generating your own primary keys too, like concurrency while generating the key, or running out of values. So, consider both options and go with the one that suits you best.

  • Minimize the use of NULLs, as they often confuse the front-end applications, unless the applications are coded intelligently to eliminate NULLs or convert the NULLs into some other form. Any expression that deals with NULL results in a NULL output. ISNULL and COALESCE functions are helpful in dealing with NULL values. Here’s an example that explains the problem:

    Consider the following table, Customers which stores the names of the customers and the middle name can be NULL.

    CREATE TABLE Customers
    (
    FirstName varchar(20),
    MiddleName varchar(20),
    LastName varchar(20)
    )

    Now insert a customer into the table whose name is Tony Blair, without a middle name:

    INSERT INTO Customers 
    (FirstName, MiddleName, LastName) 
    VALUES (‘Tony’,NULL,’Blair’)

    The following SELECT statement returns NULL, instead of the customer name:

    SELECT FirstName + ‘ ‘ + MiddleName + ‘ ‘ + LastName FROM Customers

    To avoid this problem, use ISNULL as shown below:

    SELECT FirstName + ‘ ‘ + ISNULL(MiddleName + ‘ ‘,”) + LastName FROM Customers

  • Use Unicode datatypes, like NCHAR, NVARCHAR, or NTEXT, if your database is going to store not just plain English characters, but a variety of characters used all over the world. Use these datatypes only when they are absolutely needed as they use twice as much space as non-Unicode datatypes.
  • Always use a column list in your INSERT statements. This helps in avoiding problems when the table structure changes (like adding or dropping a column). Here’s an example which shows the problem.

    Consider the following table:

    CREATE TABLE EuropeanCountries
    (
    CountryID int PRIMARY KEY,
    CountryName varchar(25)
    )

    Here’s an INSERT statement without a column list , that works perfectly:

    INSERT INTO EuropeanCountries
    V
    ALUES (1, ‘Ireland’)

    Now, let’s add a new column to this table:

    ALTER TABLE EuropeanCountries
    ADD EuroSupport bit

    Now run the above INSERT statement. You get the following error from SQL Server:

    Server: Msg 213, Level 16, State 4, Line 1
    Insert Error: Column name or number of supplied values does not match table definition.

    This problem can be avoided by writing an INSERT statement with a column list as shown below:

    INSERT INTO EuropeanCountries
    (CountryID, CountryName)
    VALUES (1, ‘
    England‘)

  • Perform all your referential integrity checks and data validations using constraints (foreign key and check constraints) instead of triggers, as they are faster. Limit the use triggers only for auditing, custom tasks and validations that cannot be performed using constraints. Constraints save you time as well, as you don’t have to write code for these validations, allowing the RDBMS to do all the work for you.
  • Always access tables in the same order in all your stored procedures and triggers consistently. This helps in avoiding deadlocks. Other things to keep in mind to avoid deadlocks are: Keep your transactions as short as possible. Touch as few data as possible during a transaction. Never, ever wait for user input in the middle of a transaction. Do not use higher level locking hints or restrictive isolation levels unless they are absolutely needed. Make your front-end applications deadlock-intelligent, that is, these applications should be able to resubmit the transaction in case the previous transaction fails with error 1205. In your applications, process all the results returned by SQL Server immediately so that the locks on the processed rows are released, hence no blocking.
  • Offload tasks, like string manipulations, concatenations, row numbering, case conversions, type conversions etc., to the front-end applications if these operations are going to consume more CPU cycles on the database server. Also try to do basic validations in the front-end itself during data entry. This saves unnecessary network roundtrips.
  • If back-end portability is your concern, stay away from bit manipulations with T-SQL, as this is very much RDBMS specific. Further, using bitmaps to represent different states of a particular entity conflicts with normalization rules.
  • Always add a @Debug parameter to your stored procedures. This can be of BIT data type. When a 1 is passed for this parameter, print all the intermediate results, variable contents using SELECT or PRINT statements and when 0 is passed do not print anything. This helps in quick debugging stored procedures, as you don’t have to add and remove these PRINT/SELECT statements before and after troubleshooting problems.
  • Do not call functions repeatedly within your stored procedures, triggers, functions and batches. For example, you might need the length of a string variable in many places of your procedure, but don’t call the LEN function whenever it’s needed, instead, call the LEN function once, and store the result in a variable, for later use.
  • Make sure your stored procedures always return a value indicating their status. Standardize on the return values of stored procedures for success and failures. The RETURN statement is meant for returning the execution status only, but not data. If you need to return data, use OUTPUT parameters.
  • If your stored procedure always returns a single row result set, consider returning the result set using OUTPUT parameters instead of a SELECT statement, as ADO handles output parameters faster than result sets returned by SELECT statements.
  • Always check the global variable @@ERROR immediately after executing a data manipulation statement (like INSERT/UPDATE/DELETE), so that you can rollback the transaction in case of an error (@@ERROR will be greater than 0 in case of an error). This is important, because, by default, SQL Server will not rollback all the previous changes within a transaction if a particular statement fails. This behaviour can be changed by executing SET XACT_ABORT ON. The @@ROWCOUNT variable also plays an important role in determining how many rows were affected by a previous data manipulation (also, retrieval) statement, and based on that you could choose to commit or rollback a particular transaction.
  • To make SQL Statements more readable, start each clause on a new line and indent when needed. Following is an example:

    SELECT title_id, title
    FROM titles
    WHERE title LIKE ‘%Computer%’ AND
          title LIKE ‘%cook%’

  • Though we survived the Y2K, always store 4 digit years in dates (especially, when using cCHAR or INT datatype columns), instead of 2 digit years to avoid any confusion and problems. This is not a problem with DATETIME columns, as the century is stored even if you specify a 2 digit year. But it’s always a good practice to specify 4 digit years even with DATETIME datatype columns. 
  • As is true with any other programming language, do not use GOTO, or use it sparingly. Excessive usage of GOTO can lead to hard-to-read-and-understand code.
  • Do not forget to enforce unique constraints on your alternate keys.
  • Always be consistent with the usage of case in your code. On a case insensitive server, your code might work fine, but it will fail on a case sensitive SQL Server if your code is not consistent in case. For example, if you create a table in SQL Server or a database that has a case-sensitive or binary sort order, all references to the table must use the same case that was specified in the CREATE TABLE statement. If you name the table as ‘MyTable’ in the CREATE TABLE statement and use ‘mytable’ in the SELECT statement, you get an ‘object not found’ error.
  • Though T-SQL has no concept of constants (like the ones in the C language), variables can serve the same purpose. Using variables instead of constant values within your queries improves readability and maintainability of your code. Consider the following example: 

    SELECT OrderID, OrderDate
    FROM Orders
    WHERE OrderStatus IN (5,6)

    The same query can be re-written in a mode readable form as shown below:

    DECLARE @ORDER_DELIVERED, @ORDER_PENDING
    SELECT @ORDER_DELIVERED = 5, @ORDER_PENDING = 6

    SELECT OrderID, OrderDate
    FROM Orders
    WHERE OrderStatus IN (@ORDER_DELIVERED, @ORDER_PENDING)

  • Do not use column numbers in the ORDER BY clause. Consider the following example in which the second query is more readable than the first one:

    SELECT OrderID, OrderDate
    FROM Orders
    ORDER BY 2

    SELECT OrderID, OrderDate
    FROM Orders
    ORDER BY OrderDate



Naming conventions

 Stored Procedures

Stored procedure names should conform to the following convention:

AppName_ActionName< ?xml:namespace prefix ="" o ns ="" "urn:schemas-microsoft-com:office:office" />

e.g. HES_GetOfferDetails

 

Property

Description

AppName

Name of the application/system that uses the stored procedure. E.g. “AM” (AdMaker),” HES”,” CPT”, etc

In some cases it could be a variant of the application, e.g. “VHES_Admin”

ActionName

Name of the action using Pascal notation. This should start with a verb (e.g. Get, Update, Delete…).

 E.g: GetOperators, AuthenticateUser, InsertOffer, DeleteRegion, Upd ateDPN

 


Additional Information Within Stored Procedures

Each stored procedure should include supplementary information that covers:

·         Author and creation date

·         Short description of what the stored procedure does

·         Description of input parameters (when not too obvious). Default values can be specified in the format: “[12]”.

·         Where it is used (platform, section, etc)

If any modifications are made to an existing stored procedure then the following additional information should be provided each time:

·         Author of the modifications and the date they were made

·         Short description of the changes made

 

Example header (with modifications):

/************************************************************

 AN – < ?xml:namespace prefix ="" st1 ns ="" "urn:schemas-microsoft-com:office:smarttags" />31/10/00

 Description: Returns all destinations for a particular group.

 Input: @GroupId: Group Id (from table DestinationGroups) [1]

************************************************************

History:

 

AN – 02/01/01

Modification to the number of fields returned by this stored procedure

 

AN – 04/08/03

Added FieldId field in the select statement

************************************************************/

 

Tables

a)     Table names

Use a descriptive name use Pascal notation. Tables will normally be one or more nouns that should be expressed in plural. E.g. AccommodationTypes, Offers.

When creating a table that link two other tables use the form <table1>To<table2>. E.g. MasterToDetail.

 

b)     Fields

When naming fields within tables, the following method should be used when naming primary and foreign keys:

In the table with the primary key: PrimaryTable (TableNameID, FieldName1, FieldName2…)

In the table with the foreign key: FKTable (PrimaryTableID, FieldName1, FieldName2…)

Use the singular form for the primary key field; i.e. use OfferID instead of OffersID.

For example if the table Users had a primary key called UserID and this was used as a foreign key in the table Addresses you should use:

 

Table name

Fields

Users

UserID, Password, CreationDate, LastLogIn

Addresses

AddressID, UserID, HouseNumber, RoadName, Town, Postcode

 

 

c)      Indexes and foreign keys

With respect to Indexes and Foreign keys the following conventions should be adopted:

Index                     -               IX_<TableName>_<ColumnName1>_<ColumnName2>…

Foreign Key         -               FK_<FKTable>_<PrimaryTable>

Idx and FK are prefixes indicating an index and a foreign key respectively, TableName is the name of the table concerned and ColumnName is the name of a column that is included.

PrimaryTable is the table that contains the primary key and FKTable is the table that contains the foreign key. Use abbreviations when the table names are too long. 

Examples of valid foreign keys and indexes for this example:

-          IX_HolidayOffers_Price_Nights: index on fields Price and Nights from HolidayOffers table.

-          FK_HolsOffersToOfferTypes_OfferTypes: Foreign key from HolsOffersTo OfferTypes to OfferTypes.

Views

Use a descriptive name in Pascal notation.

 


3         Annex A – Pascal notation

The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters.

For example: BackColour, TradingName, TelephoneSet.

·        Developer: Acquire a good understanding of the effect a query has on the underlying database.< ?xml:namespace prefix ="" o ns ="" "urn:schemas-microsoft-com:office:office" />

·        DBA: Perform regression testing and trend-analysis when moving any code (in application or database) from development servers to QA/test servers and onto production.

·        DBA: Make sure proper indexes are in place.

·        DBA: Make sure each table has a clustered index.

·        Developer: Making sure to review complex queries with the DBA.

·        DBA: Use read-only copies of databases to accommodate heavy reporting requirements during business hours or limit certain resource intensive queries to off-hours.

·        Developer: Make sure to use read-only, forward-only, result sets whenever possible, and fetch all result set data in the application immediately.

·        DBA: Make sure you are aware of developer requirements, the developer tools being used, and provide feedback to catch potential problems early.

·        DBA: Make sure to select the RAID solution that best supports your needs.

·        DBA: Make sure there is sufficient memory on the server.

·        DBA: Proactively monitor the server hardware to make sure it can handle any increasing loads.

·        DBA and Developer: Speak with the end-users to make sure they are happy with performance.

·        DBA and Developer: Don’t assume pre-packaged applications (like customized CRM applications, SQL access or reporting tools) generate efficient SQL.

·        DBA and Developer: Proactively monitor SQL activity on SQL Server.

·        DBA and Developer: Avoid SQL cursors whenever possible.

·        DBA and Developer: Keep SQL transactions as short as possible.

·        DBA: Avoid running extraneous services on the server running SQL Server.

·        DBA: Make sure that Microsoft’s Internet Information Server (IIS) or other web servers are on a different “box” than SQL Server.

·        DBA and Developer: Use stored procedures for data access wherever possible.

·        DBA: Backup to disk first (staging), and then copy the disk backup to tape.

·        DBA: Keep index and column statistics up-to-date.

·        DBA and Developer: Avoid table and index scans wherever possible.

·        DBA and Developer: Avoid non-optimizable selection criteria in SQL statements, such as “not equal” comparisons in WHERE clauses.

  • DBA and Developer: Only request the rows and columns needed for processing.

« Previous PageNext Page »