Logic’s Last Stand

January 30, 2010

Chess: An Introduction to Opening Theory

Filed under: Gaming — Tags: , , , — Zurahn @ 11:37 pm

Chess Openings – A Beginner’s Guide

Opening Rules

When players of significantly different skill levels play, it is common for the game to be decided in the opening itself, before the better player even really has to think. Without proper understanding of the opening, the game can be lost before it’s even started, or at the least have a more difficult position to play from, making the rest of the game that much harder. Throughout this tutorial, I will refer to rules by which to play. Given that the value of a move is dependent on its situation, these rules are not hardline laws, but general guidelines by which to consider potential moves.

At the start of the game, white has a slight advantage by nature of having the first move, and his goal in the opening is to maintain the advantage that bestows, or improve upon it. Conversely, black intends to gain equality. The method by which this is done is the same for both sides.

Fig. 1-1

Fig. 1-1

Players need the control the central squares (fig. 1-1) in order to have a foothold to manoeuvre pieces into an attack on the king. Without control of the board, primarily stemming from the centre, there is often little that can be done to facilitate an attack.

 

I.A. Horowitz (How to Win in the Chess Openings) on the practical reasons for controlling the central squares,

“…the squares in the center of the board are the more important ones. The reason they are more important becomes apparent when the squares are considered in terms of a network of interlinked paths. It is clear that the player who controls the hub of the network can send his men from one side of the board, directly through the hub, to the other side of the board with ease. Whereas the player who does not control the hub must send his men from one side of the board to the other via devious routes, time-consuming routes. As time is an important factor in chess–that is, as it is important to reach a goal in the least number of moves–it follows that it is important to control the central squares.”

 

The question then becomes how it is best to do this. As mentioned by Horowitz, time is very important, and thusly you not only want to control those central squares, but be as efficient as possible in doing so. This leads us to the first rule in openings, which is that pawns are not developing moves. I’ll allow Aron Nimzowitsch (My System) to elaborate.

“A pawn move must not be considered in itself a developing move, but rather simply a move that aids development … However an advance without pawns is unsustainable, because our opponent’s pawn centre, thanks to its desire to expand, would repel those of our pieces which were already developed.”

We can by this rule determing that moves such as 1. a4 are incorrect, as they neither support development nor aid control of central squares.

 

Relating to efficiency, we can easily see that any piece can move to a position that attacks the centre in a single move, so a new rule emerges, our second, from this, which is only move a piece once in the opening. If you are moving a piece more than once, you’re being inefficient and wasting time.

Pieces have different strengths and weaknesses, and their values are relative to the position. This is best illustrated by the difference between knights and bishops. Knights are best utilized in closed positions where pawns are locked and manoeuvering is difficult, due to their nature of being able to leap over other pieces. Bishops, conversely, are best in open positions, particularly when still paired with the opposite coloured bishop. This leads us to our third rule, which is knights before bishops. Knights in opening positions tend to control more squares and are more mobile in opening moves.

 

A consequence of the leapfrogging ability of knights is the basis for a third rule of the opening, which is protect pawns with knights not bishops or pawns. Given a choice between a knight or either a bishop or another pawn, choose a knight to protect a pawn. A weakness of bishops is that a pawn in the way limits the scope of its attack; guarding a pawn with a bishop is to intentionally gimp it. Guarding a pawn with another pawn in the opening can lead to poor pawn structure.

Continuing on pawn structure, despite pawns not being developing moves, the purpose and utility of pawns is arguably the single most important concepts not just in the opening, but the entire game. In the opening, pawns dictate the flow of development; in the middle-game, they are the focus of position and tactics; and in the end-game, they are the deciding factor to end or draw the game.

To illustrate the effect pawn structure can have, consider the following common opening mistake by black,

 

Fig. 1-2

Fig. 1-2

1. e4 e5 2. Nf3 f6 3. Nxe5! fxe5? 4. Qh5+

 

We can see the resulting position (fig. 1-2) where black has no way to prevent a loss of material. If 4..g6 then 5. Qxe5+ Qe7 6. Qxh8 wins the rook. Alternatively, 4..Ke7 is even worse, losing to 5. Qxe5+ Kf7 6. Bc4+ and black has a lot of problems. The kingside has fewer pawns, so moving the f-pawn, particularly early, is often dangerously weakening. Having pawns support other pawns by necessity opens holes on the opposite colour and is a risk that must be assessed.

Opening Examples

Ultimately, by how different the strategies vary depending on the opening, it is necessary in order to understand the opening to go through some examples of the most common openings to get an idea of why the moves are played as they are. We will then look at an example game for each where one side goes wrong in the opening, leading to an early demise.

King’s Gambit

The King’s Gambit is an opening that was the most common opening in the 19th century when the popularity of romantic chess–playing wild attacking games with lots of sacrifices–was at its peak. It creates tactical positions that are dangerous for both sides. It is characterized by the sequence 1. e4 e5 2. f4

For the sake of this example, we will only look at the King’s Gambit Accepted where black captures the f-pawn. An example continuation here is the Muzio gambit; this is a sacrifice that is considered dubious (a poor move with correct play), but illustrates the kind of attacking chances the opening tends to lead to.

Fig. 2-1

Fig. 2-1

1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O?! gxf3 6. Qxf3

 

This position (fig. 2-1) has black with a material advantage, but white has a very strong attack, bearing down on the f-file and black’s weakened kingside. This attack is a benefit of placing development above material. Numerically speaking, weighing a pawn at 1 and a knight at 3, the position is -2.0 in favour of black. However, with the positional evaluation in mind, it is more along the lines of a -0.5 to -1.0 position, meaning despite the usually game-losing material definite of 2 pawns worth, white is still well within fighting chances.

An example game is myself versus an online user username SKWERLY, 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. Bc4 Nf6 5. Nc3 Be7 6. d4 O-O 7. Bxf4 Nc6 8. O-O Bg4 9. Qd2 Na5? 10. Bd3 b6 11. Rae1 c5 12. e5 dxe5 13. dxe5 Nd5 14. Nxd5?? Qxd5 15. Bxh7+! Kxh7 16. Qxd5

 

 

In this game, black pushes pawns along the queenside flank neglecting development and ceding the centre and even kingside to white’s discretion. White quickly completes development and his pressure immediately causes black to blunder. Black was doing just find until move 9, and just three wasted moves meant disaster. The key to black’s position in the King’s Gambit is essentially just completing development while withstanding white’s attack. Proper play and he’ll come out just find; the king’s defence is key. On white’s side, he has to worry about not being pushed back by counterplay, and not being overly aggressive, however tempting it may be.

Queen’s Gambit Declined

The Queen’s Gambit provides a good juxtaposition to the King’s Gambit in many ways. It starts 1. d4 d5 2. c4 offering up the c4 pawn. The most common response is for black to decline the gambit, and the position thusly remains relatively closed. There is no way for black to take the pawn and avoid white eventually recapturing, so there’s no material gain for a relative positional loss. There are fewer tactics and much more prophylactic play.

The classical defense is still common — though not without other options — and runs as follows

Fig. 2-2

Fig. 2-2

1. d4 e6 2. c4 d5 3. Nc3 Nf6 4. Nf3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4

 

The position (fig. 2-2) has white holding more space, while black has a tight defense. The key square for black is the d5-square to act as a strong central position for a knight, or force a breakthrough up the middle resulting in an exchange of pieces. Typically the capture seen on move 8 by black follows white’s development of his bishop to d3 in order to win a tempo. Also, black’s c-pawn in this an other variations will support the centre moving most often to c6 or in the Tarrasch variation, c5. Both sides will castle kingside as the queensides will be too weakened in terms of the pawn structure.

The game I’ll use as an example is another online game, this time against user “Leon”. 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Nf3 Nc6 6. e3 b6 7. Bxf6 gxf6 8. cxd5 exd5 9. Qa4 Qd7 10. Bb5 Bb7 11. O-O O-O-O 12. Rfc1 Rhg8 13. Nxd5 Qxd5 14. Bxc6 Bxc6 15. Qxc6 Rd7 16. e4 Qxc6 17. Rxc6 Rg4 18. Re1 Bb4 19. h3 Rf4 20. Re3 Re7 21. g3 Rfxe4 22. Rxe4 Rxe4 23. Rxf6 c5 24. a3 Be1 25. Kf1 cxd4 26. Nxe1 1-0

 

 

In this game, black developes his b1 knight to a bad square on c6, as it blocks the c-pawn’s support in the centre, then blunders on the proceeding move, as he by pushing the b pawn, he loses a defender of the knight, allowing white to capitalize with heavy pressure. 13. Nxd5 while complicated somewhat by the number of pieces and the discovered attack introduced, it is essentially just an exchange to win a pawn, as black is short one defender and loses a pawn as a result. At this point, white has a significant advantage, and leads to a further game-ending blunder. The game is straight-forward for white, making typical opening manoeuvres for the position, then following logically from there.

Reti Opening

The Reti opening is simply 1. Nf3. The reason I don’t choose a particular line for this opening is that most often it transposes into lines from a different opening. For example, 1. Nf3 d5 2. d4 Nf6 3. c4 and the game has transposed into the Queen’s Gambit.

We’ll take a look at a Reti-specific line wherein white takes a dynamic approach to controlling central squares referred to as hyper-modernism, popularized in the early 20th-century, with Richard Reti being a key proponent along with the likes of Aron Nimzowitch and Ksawery Tartakower.

Fig. 2-3

Fig. 2-3

1. Nf3 d5 2. c4 e6 3. g3 Nf6 4. Bg2 Be7 5. O-O O-O 6. b3 c5 7. Bb2 Nc6

 

In the example (fig. 2-3) you can see that unlike more classical constructs, white takes more of a distance approach. The main danger of the approach is that it’s easy to lose space. If white starts the game with 1. Nf3 it is a safe bet it will result in a kingside castle. If the game does not transpose into a Queen’s Gambit game, it’s also common to fianchette the kingside bishop. White will want to control the long diagonals and keep them open, while black will look to expand his space and break up white’s pawn structure.

For a specific example, I will choose one of the favourite games I ever played, which was using the King’s Indian Attack in this game, Zurahn – rattle.

 

1. Nf3 Nf6 2. g3 d5 3. Bg2 e6 4. O-O Bd6 5. d3 O-O 6. c4 c6 7. Nc3 Na6 8. Bg5 h6 9. Be3 Bc5 10. Bxc5 Nxc5 11. d4 Na6 12. b3 Qa5 13. Qd2 Bd7 14. Nxd5 Qxd2 15. Nxf6+ gxf6 16. Nxd2 Nb4 17. Ne4 Kg7 18. Rfd1 Rad8 19. e3 Bc8 20. c5 Nd5 21. Nd6 a5 22. Rac1 Nb4 23. a3 Nd5 24. e4 Nc7 25. f4 e5 26. d5 Nb5 27. Nxb5 cxb5 28. Kf2 exf4 29. gxf4 Rfe8 30. Ke3 f5 31. e5 f6 32. e6 Re7 33. Kf2 Kh8 34. Re1 Rde8 35. d6 Rxe6 36. Bxb7 Bxb7 37. Rxe6 Rxe6 38. d7 Re4 39. d8=Q+ 1-0

 

In the game, issues stemming from the opening permiate through the rest of the game. The passive 3..e6 followed by the awkward and misplaced 4..Bd6 attacking an overprotected g6 pawn allow white to get the jump. On white’s side, though, 8. Bg5 is pointless without intention of capturing on f6, because the bishop would be trapped after 8..a6 9. Ba4 b5. Finally, if you look at the position as of move 16, we see black has a very bad bishop and a knight on the flank, along with doubled pawns on a weakened kingside. White alternatively has a strongly placed bishop, a knight a little back, but out of danger and ready to join the attack, and a safe king to add to the pawn material advantage.

English Opening

Another opening identifiable by its first move, the English opening is 1. c4. This was my stomping ground for learning the openings; it is relatively easy to open with a solid position, but it’s not without the opportunity for tactics. There are transposition options as well, and being the fourth most common opening, it is relatively unexpected at lower levels. Typical lines play like a reversed Sicilian, with white performing a fianchetto on the kingside bishop if not both sides, and often castling kingside early.

To show the dynamics of the position, we’ll look at one such common development from the opening.

Fig. 2-4

Fig. 2-4

1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bb4 5. Bg2 O-O 6. O-O

 

The basis of all developments surrounds the e5 pawn and handling the potential push to e4 attacking the f6 square. Because of this, I am partial to playing an earlier e6 in this or similar situations as opposed to castling first, which in this case would follow 6..e4 7. Ng5 Bxc3 8. bxc3 Re8 9. f3 exf3 10. Nxf3.

A temptation in this opening in particular is to play a stonewall, which is to say two forward pawns creating a backward pawn to protect them. For example, 1.c4 e5 2. e4. This is a poor move and rarely is this kind of position beneficial. Backward pawns are weak and targets, and this position creates holes in the defence and control of the centre.

Illustrating how white can go wrong in the opening, I have an example of Big Cat – Zurahn.

1. c4 e5 2. Nc3 Nf6 3. Nf3 d5 4. cxd5 Nxd5 5. e4 Nb6 6. d3 Nc6 7. Be2 Bc5 8. O-O Be6 9. Bg5 Qd7 10. Be3 Bd4 11. Ng5 h6 12. Nxe6 Qxe6 13. Bg4 Qe7 14. Re1 Rd8 15. Nb5 Bxb2 16. Rb1 Bd4 17. Nxd4 Nxd4 18. Bxd4 Rxd4 19. Qf3 O-O 20. Qe3 Rfd8 21. Be2 R8d6 22. f4 exf4 23. Qxf4 c5 24. e5 Rxf4

 

Here we see relatively typical developments, but 5. e4 is a little odd. But the key problem is following that with 6. d3, creating a backward pawn and a perminent weakness on d4 that exploited for the entirety of the game. It’s not losing unto itself, typically none of these opening errors are, but they mean white has to play more accurately to keep up. The harder you make it on yourself, the more often you’re going to make a mistake.

Sicilian Defense

It is common that a defence is dependent on white’s opening, and characterized as such, as seen in the Queen’s Gambit, for example, where black’s choice is simply accepted or declined. However, there are instances where black’s choice are so prominent that they warrant a name of its own. Such is that of the single most common opening in high level chess, that being the Sicilian.

The Sicilian Defense is simply 1. e4 c5. It creates an imbalanced position where black has a lot of control over the flow of the game. There are various lines of play, but there are common themes.

I’ll use the Sicilian Accelerated Dragon variation as an example.

Fig. 2-5

Fig. 2-5

1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 O-O 8. Bb3 d6 9. f3 Bd7 10. Qd2 Rc8 11. O-O-O

 

Here, while this is just one specific line, there are several moves and themes common to the opening lines as a whole. White is a general rule always follows 1..c5 with Nf3 followed by d4. There are complications if he doesn’t. Similarly, white almost always castles queenside while black kingside, if at all. The black g8 knight develops to f6, but the b8 knight depending on the variation may develop to d7. This all culminates to a pawn rush on the kingside by white, while black has counterplay on the queenside.

The example game here is against a chess engine. Modern chess engines are terrific in the opening not because of processing power and the quality of the algorithm, but because of near-perfect opening books. An engine not making good use of an opening book can run into problems. The game here is Zurahn – ProDeo 1.1.

1. e4 d6 2. Nf3 c5 3. d4 Nf6 4. Nc3 cxd4 5. Nxd4 g6 6. Be3 Bg7 7. Bc4 Nc6 8. Qd2 O-O 9. f3 Bd7 10. h4 Rc8 11. Bb3 Ne5 12. O-O-O h5 13. Rdg1 a5 14. a4 Nc4 15. Bxc4 Rxc4 16. g4 hxg4 17. h5 gxh5 18. Bh6 Rxd4 19. Qg5 Ne8 20. Rxh5 f5 21. Bxg7 Nxg7 22. fxg4 e5 23. gxf5 Qxg5+ 24. Rhxg5 Rf7 25. f6 Bc6 26. Rxg7+ Rxg7 27. Rxg7+ Kf8 28. Nb5 Bxb5 29. axb5 Rxe4 30. Rxb7 a4 31. b6 Re1+ 32. Kd2 Rb1 33. Ra7 Rxb2 34. b7 d5 35. Ra8+ Kf7 36. b8=Q Rxb8 37. Rxb8 Kxf6 38. Ra8 Ke6 39. Rxa4 Kd6 40. Ra6+ Kd7 41. Kc3 Ke7 42. Kb4 Kd7 43. Kc5

 

We can see that there are a lot of typical development moves, but it seems the book runs out too early for ProDeo as it begins grabbing materialistically and ignoring the danger of a kingside attack. White’s position is quite comfortable for the king while the pressure builds up on black. If there’s one move that hurt, it was 14..Nc4, trading off a well-placed knight in the centre of the board for the sake of breaking up the bishop pair. In the Sicilian Dragon and Accelerated Dragon variations, white intends to trade off the dark-squared bishop, anyway, so losing the bishop pair is less of a concern.

King’s Indian Defense

Another popular high-level opening, it’s a response to white’s 1. d4 with 1..Nf6. Though the position is largely positional in nature, it can quickly become a tactical headache. Black will early on get himself into a crampt position, but will have the opportunity to gain space on the kingside. This becomes a bit of an arms race where white presses the queenside while black looks to break through on the kingside.

 

Fig. 2-6

Fig. 2-6

1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7

 

From here, there are a few different routes to take, such as 9. Ne1 (Mainline), 9. b4 (Bayonet Attack), or 9. Nd2 (Classical), but all routes lead to white and black attacking the opposite side. Your common themes are black manoeuvering his knights on the kingside to support a pawn storm, and white breaking through on the c-file, and not maintaining a knight on f3.

The King’s Indian Defense is a very precise opening, so much deviation from the typical solid moves can lead to problems. We’ll see this in Rorticus – Zurahn where white gets too aggressive.

1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. e5 dxe5 7. Nxe5 c5 8. d5 Bf5 9. Bd3 Nxd5 10. Bxf5 Nxc3 11. Qb3 Bxe5 12. bxc3 gxf5 13. Bb2 Bf4 14. Rd1 Qc7 15. g3 Qe5+ 16. Kf1 Qe4 17. Rg1 Bg5 18. Re1 Qf3 19. Re3 Bxe3 20. Ke1 Qxf2+ 21. Kd1 Rd8# 0-1

 

The problems for white begin with 6. e5. It’s the first move out of book, and for good reason it’s not the typical move here. If black recaptures with the d-pawn, the trade of queens leaves white unable to castle, so the forced second move of the knight is what is played. Black plays the correct continuation c5, which forces the removal of the d4 pawn from defending the knight on e5, which will become threatened by the bishop on g7. Again this leads into a difficult position, where white blunders with 10. Bxf5 which leads to a winning advantage.

Conclusion

The opening isn’t the only facet of the game. In fact, at high levels, the first 10 moves or so most often are irrelevant, and even criticised for making the game about memorization as opposed to over-the-board evaluation and creativity, helping give rise to Fischer Random Chess. That being said, until your at that Master or higher levels, knowing the fundamentals isn’t going to be that simple. It affects the outcome of the rest of the game, and at the least makes it easier or harder depending. Basic concepts like Knights before Bishops before Rooks before Queen, controlling the centre, defending the king, and the important of tempo all give you a leg up over anyone who is unfamiliar with them. With simple, solid opening play, you’ll start to see games decided before you’ve even really had to think, and that’s something to think about.

Advertisements

November 26, 2008

Very Simple JavaScript Image Viewer

Filed under: Computers — Tags: , , , — Zurahn @ 2:21 am

Being in need of a relatively simple inline viewer for a series of images, I opted to make my own instead of looking to the many premade options with far more detail than I’d need. While I’ll probably spruce my own option up from the bare-bones, I thought the baseline was a nice example piece of how to keep things simple in a time when there’s a tendency to move towards frameworks such as jQuery, which while excellent in many instances, aren’t always necessary.

I’m not a fan of JavaScript’s implementation of objects, so I generally avoid them. However, in this case it seemed rather suitable. Just pass the element ID of what you want to contain the images, along with an array of images to the Gallery constructor, then run the init function with the IDs of the navigation buttons on page load.

The navigation was the part I was a bit torn on. Optimally it would be part of the actual gallery code and not something that needed to be added separately; the problem is that in order to call the next() and prev() functions for the object, I need the actual Gallery object that is created. The only other option was a “setClassObject” function to provide the actual gallery object, but that would get needlessly obtrusive.

/* 
  File: gallery.js  
*/

function Gallery(id, imgs)
{
  this.id = id;
  this.imgs = imgs;
}

function init(prevID, nextID)
{
  if(nextID != null)
    this.nextObj = document.getElementById(nextID);
  if(prevID != null)
    this.prevObj = document.getElementById(prevID);
  this.curFrame = 0;
  var output = '';
  output += '<div id="'+this.id+'_images"><img src="'+this.imgs[this.curFrame]+'" id="'+this.id+'_image_'+this.curFrame+'" alt="" /></div>';
  document.getElementById(this.id).innerHTML = output;
  this.updateImage();
  this.updateButtons();
}

function next()
{
  this.curFrame++;
  this.updateImage();
  this.updateButtons();
}

function prev()
{
  this.curFrame--;
  this.updateImage();
  this.updateButtons();
}

function updateImage()
{
  document.getElementById(this.id+'_images').childNodes[0].src = imgs[this.curFrame];
}

function updateButtons()
{
  var len = this.imgs.length;
  if(typeof this.nextObj != 'undefined')
  {
    if(this.curFrame == len-1)
	  this.nextObj.disabled=true;
	else
	  this.nextObj.disabled=false;
  }
  if(typeof this.prevObj != 'undefined')
  {
    if(this.curFrame == 0)
	  this.prevObj.disabled=true;
	else
	  this.prevObj.disabled=false;
  }
}

Gallery.prototype.init=init;
Gallery.prototype.updateImage=updateImage;
Gallery.prototype.updateButtons=updateButtons;
Gallery.prototype.next=next;
Gallery.prototype.prev=prev;

And an appropriately simple implementation of that viewer is seen here,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="gallery.js"></script>
<script type="text/javascript">
var imgs = ['image_1.jpg','image_2.jpg', 'image_3.jpg', 'image_4.jpg'];
var gallery = new Gallery('galleryImages', imgs);
function init()
{
  gallery.init('prev', 'next');
}
window.onload=init;
</script>

<title>JavaScript Image Viewer</title>
</head>

<body>
<div id="gallery" style="text-align: center">
  <div id="galleryImages"></div>
  <div id="navigation"><input type="button" id="prev" value="PREV" onclick="gallery.prev();" />
  <input type="button" id="next" value="NEXT" onclick="gallery.next()" />
  </div>
</div>
</body>
</html>

You can see the viewer in action here

May 25, 2008

Beginner’s Guide to a Real Web-site – Part 6 – Intro to SQL

Filed under: Computers — Tags: , , , , , , — Zurahn @ 2:46 pm

Database interaction is in most cases dealt with using a language called SQL (Structured Query Language). For our purposes, we only need to know the basics, which are:
-Inserting data
-Updating data
-Deleting data
-Retrieving data

These are conveniently done using the keywords INSERT, UPDATE, DELETE and SELECT. However, before we can get to that, we need to understand what we’re storing and how to store it. We know that we simply want to store blog posts; these will have titles, dates, and a body. We can do this with a single table. A table is what we call what we store data in, because we use “columns” of data.

Our table, which we’ll call “blogs” will have these columns:
-id
-title
-date
-body

We can do this either in SQL or in the handy PHP tool phpMyAdmin which is included with WAMP (click the WAMP icon on the taskbar, and choose phpMyAdmin). PHP web hosts will typically have phpMyAdmin installed for your use. In our code we need to use SQL to interact with the database, but setting up the structure we can, and for simplicity’s sake in this tutorial, do it in phpMyAdmin.

Firstly, we create a new database, which we can call “mysite” and click the Create button. This will create the database, which will store the table. Now you’ll see at the bottom “Create new table on database mysite”. Enter “blogs” for the name, and we need 4 columns (id, title, date, body).

On the next screen, “Field” is the name of the column (id, title, date, body). For the data type dropdowns, id will be INT, title will be VARCHAR, date will be a TIMESTAMP (not DATETIME), and body will be TEXT.

INT is short for Integer (a number with no decimal points and can be positive or negative). IDs should be Integer values. Set the length to 11, EXTRA to auto_increment (meaning it automatically assigns a unique value to it when you INSERT), and choose the first radio button under the page with the key to set it as the Primary Key (the value that uniquely identifies a record — in our case a blog post — in the table).

For title, VARCHAR is a text field with a set length. We’ll set the length to 50 (seems reasonable for a maximum title length).

For date, TIMESTAMP is the number of seconds having passed since December 31, 1969. Timestamps are easily converted to date formats in PHP. Change default to ON UPDATE CURRENT_TIMESTAMP; this just means to insert the current time by default.

And for body, TEXT is a text field with no specified maximum length and is only limited by the database software itself. This will allow for blogs without having to worry about one being too long.

Click Save to create the table.

If you wanted to do this in SQL, here is the code, though I won’t go through it to explain.

CREATE TABLE mysite.blogs (
id INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
date TIMESTAMP NOT NULL,
body TEXT NOT NULL,
PRIMARY KEY (id)
) ENGINE = InnoDB 

For the sake of building our SQL skills before jumping into PHP usage, click the SQL tab in phpMyAdmin to get a box where we can enter SQL queries. This way we can test our queries and see how they work. Here’s a query to insert a record into our table

INSERT INTO blogs (title, body) VALUES('A Blog Post', 'This is where a blog post would be');

Selecting all records from a table:

SELECT * FROM blogs;

Select specific records and columns from a table:

SELECT title FROM blogs WHERE id = '1';

We can also update the record:

UPDATE blogs SET title = 'My Blog Post' WHERE id = '1';

Or, finally, delete the record:

DELETE FROM blogs WHERE id = '1';

This is basically all you’ll need for the development of our site. We can use SQL statements directly in PHP to modify the database, which we’ll do in Part 7.

April 16, 2008

Beginner’s Guide to a Real Web-site – Part 5 – PHP Programming

Filed under: Computers — Tags: , , , , , , , — Zurahn @ 5:57 am

PHP is a complete programming language, as opposed to XHTML and CSS which are mark-up languages.

Programming languages have a few simple characteristics:
-Variables that store data
-Conditional statements
-Loops

Variables in PHP begin with a dollar sign

$num = 1;

The above statement (which must end with a semi-colon) assigns a variable called “num” the value of 1.

Conditional statements check the value of a variable or variables.

if($num == 1)
{
  echo "YES!";
}
else
{
  echo "NO!";
}

The above if statement checks if the value of $num is equal to 1. If it is, the page outputs the text “YES!”, otherwise, it outputs the text “NO!”.
Anything within the { } brackets applies only for that statement.

There are other conditional operators than “==”. Here are a list of operators in PHP:
== (equal to)
=== (equal in value and in type)
! (NOT)
> (greater than)
>= (greater than or equal to)
< (less than)
<= (less than or equal to)
|| (OR)
&& (AND)

Loops repeat a section of code several times over. There are two basic kinds, the while loop and the for loop.

A for loop is designed for when you know how many times you want to go through the loop.

for($i=0;$i<10;$i++)
{
echo $i;
}

The above loop repeats 10 times, starting from 0. The loop repeats as long as $i is less than 10, and $i increments 1 each time through.
Also note
$i++
This increments the variable $i by 1. ++ is a shortcut. Equivalents to this would be
$i += 1
or
$i = $i + 1;

A while loop lasts while a condition is true.

$count = 0;
while($count < 10)
{
  echo $count;
  $count++;
}

The above loop repeats 10 times. It keeps going as long as the count, which started at 0, is less than 10. In the above case, it works identically to a for loop; however, if you have an uncertain condition, such as a random number or user-input, the number of times is unknown.

All we’re going to do to start is to receive some data from the user, then output it back.

Make a copy of index.php and call it blog.php. This will be the start of our blog page.

<?php include_once('includes/top.php'); ?>
<title>Main Page</title>
<?php include_once('includes/middle.php'); ?>
<p><h2>My Blog</h2></p>
<p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea name="blogpost" id="blogpost"></textarea><br />
<input type="submit" value="Submit" />
</form>
</p>
<?php include_once('includes/bottom.php'); ?>

There’s a bit to explain here. A form tag in HTML surrounds a series of data you want to send to the server (our PHP). In this case, we just want to submit the data to itself, so we echo out the page we’re on, which is stored automatically by PHP in the variable $_SERVER[‘PHP_SELF’]. You could just type in ‘blog.php’ to get the same effect, except it won’t work if the page gets renamed.

The input type submit sends everything within the form to the server.

Anything sent to the server (in this case with method post) in PHP will be stored in $_POST. Let’s echo out the value of the blogpost.

<?php include_once('includes/top.php'); ?>
<title>Main Page</title>
<?php include_once('includes/middle.php'); ?>
<p><h2>My Blog</h2></p>

<?php
if(isset($_POST['blogpost']))
{
  echo "<p>".$_POST['blogpost']."</p>";
}
?>

<p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea name="blogpost" id="blogpost"></textarea><br />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</p>
<?php include_once('includes/bottom.php'); ?>

All I’ve added is a check to see if there’s a value in the blogpost, and if there is, to display it in a new paragraph.

For the sake of making things look a little nicer, you can create a new CSS file called blog.css and add this to it (and don’t forget to import it into blog.php using the tag)

#blogpost
{
  width: 85%;
  border: 1px dashed white;
}

#submit
{
  border: 1px solid white;
  background-color: black;
  color: white;
}

Our problem now is that the blog doesn’t go anywhere. It needs to be stored in a database, which we’ll cover in Part 6.

April 12, 2008

Beginner’s Guide to a Real Web-site – Part 4 – Server-side Scripting

Filed under: Computers — Tags: , , , , , , — Zurahn @ 6:58 am

The veiled goal of all we’ve done to this point is to be prepared to take on a more suitable basis for creating a web-site, and that is through server-side scripting. This is the method of running a programming language on a web-server to control the HTML that is sent to the client’s browser. In this method, we can re-use one piece of code repeatedly throughout many pages.

The language we’re going to use in our example is PHP. It is a loosely typed language (rules aren’t strict) and isn’t particularly difficult to set-up or understand.

In order to run a server-side language, you need two things: The language installation, and an application server (a program to act as the server to run the language). We’ll be using PHP and Apache. The easiest way to install these is through a packaged installation such as WAMP.

WAMP stands for Windows Apache, MySQL and PHP. MySQL is database software which we’ll use one we get a handle on PHP. You can install all these individually, but the installation of MySQL can have some quirks.

Once installed, you can run the WAMP server and a tray icon will appear on your taskbar. Clicking it will give you several options. The www directory is where all your files will go. Make sure all your services are started (the icon should be white, but you can click Restart All Services to be sure), then open your web browser and enter into the address bar:

http://localhost

This should bring up a page with WAMP information if you have it installed correctly.

In your www folder, delete index.php and create replace it with a blank index.php. Copy over the contents of index.html and open localhost in your browser again. We should see our page.

What we need to do now is segment the page. We will be using includes to do this. Though there are object-oriented ways that are generally an improvement, it goes beyond our scope and would serve at this point only to confuse.

Create a folder called “includes” and in it a file called “top.php”. This will contain our doctype declaration and opening down to the header. Copy this code and put it in top.php

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" />

Do not copy in the title tag. Save and close the file. Create a new file called middle.php and paste this code into it

</head>
<body>
<div id="container">
  <div id="header">
	<h1>Web-Design HQ</h1>
  </div>
  <div id="main">
    <div id="menu">
	Menus
    </div>
    <div id="article">

Save and close the file, and make one final file called bottom.php and paste this code into it.

	</div>
  </div>
</div>
</body>
</html>

Now, back in the index.php file, we can use our other files to easily insert our page design.

<?php include_once('includes/top.php'); ?>
<title>Main Page</title>
<?php include_once('includes/middle.php'); ?>
This is the index page
<?php include_once('includes/bottom.php'); ?>

That’s all that needs to be in index.php now.

The <?php indicator denotes the start of PHP code. You cannot place HTML within this.
include_once is a method. A method is a reusable piece of code, in this instance, to import data from another file.

So in plain terms
-Include the top part of the page up until the <head> tag
-Insert anything specific that needs to be in there, such as the title
-Include the middle section up until where we put our content
-Write our content
-Include the bottom part to close any remaining tags

Now any change we make to any of the included files will apply to every page that includes them. This significantly reduces redundant code and time wasted on repetitious changes.

Part 5 will address the basics of actual programming in PHP.

April 6, 2008

Beginner’s Guide to a Real Web-site – Part 2 – Intro to CSS

Filed under: Computers — Tags: , , , , , , — Zurahn @ 1:26 am

In Part 1 we looked at the structure of a web-page with HTML. Now we’ll look at the presentational aspects using CSS.

Create a file called main.css – This will be the main file for our CSS. Also, create a folder called “css” and place the CSS file in it. This is a good practice to organize your code. You also have the option of doing the same with your HTML files, but that’s your call (note that if you do this, the path to the other files will be different). Before we add anything to it, we need to import the CSS file to our HTML document.

<head>
  <link rel="stylesheet" type="text/css" href="css/main.css" />
</head>

The link tag is placed between the tags and has three attributes to be XHTML complient: rel, type and href. Rel is used to tell the browser that it’s importing a presentational file, type tells it the format of the file, and href tells it the actual file to import, in this case the main.css located in the folder CSS. The slash at the end is a shortcut for closing a tag that has nothing inbetween it. is the same as saying .

Here are some things to know about file paths, based on examples
href=”main.css” – the file is in the same directory
href=”/main.css” – the file is in the top directory. For example if you have index.html in C:\Web\Files\, “/main.css” looks for main.css in C:\.
href=”css/main.css” – the file is a folder called “css” in the same directory
href=”../main.css” – the file is the folder above the current directory. For example, if you have index.html in C:\Web\Files\, it looks in C:\Web\

Back on task, we’ve imported the CSS file, so let’s add something to it. Let’s organize our div tags first and foremost. Before we start making things pretty, let’s get everything set up first.

#container
{

}

#header
{

}

#main
{

}

#menu
{

}

#article
{

}

A # sign indicates an id tag, which we placed on our div tags. The { } brackets contain the code for that particular element. Let’s make the sidebar act like a sidebar, and add borders for clarity of the boundaries.

#header
{
  text-align: center;
  border: 1px solid black;
}

#menu
{
  border-right-width: 2px;
  border-right-color: blue;
  border-right-style: dotted;
  float: left;
}

#article
{
  border-left-width: 2px;
  border-left-color: black;
  border-left-style: solid;
  float: right;
}

Save that and refresh your page in the browser. It’s still not much, but it’s looking a little more familiar.

The syntax for CSS is simple,
element-attribute: value

So for text-align: center, text is the element, align is the attribute and center is the value. Thus moving the text to the center of the page in the header. This works in a div tag because div tags are by default 100% the width of its containing element (which is another div, which is the width of the screen by default).

Using “float” though, changes this, and makes the width only that required for the div. So if you added text-align: center to menu or article, you wouldn’t see a difference because the text is the width of the div.

float makes a tag ignore the placement of those around it, allowing the two divs (which are block-level elements) sit side-by-side. Just note that some will use a table to do this, which is a bad idea. I’ll explain why at a later time.

The last thing to explain are the borders. There are shortcuts in CSS so that you don’t have to write out the individual attribute every time. In the header, we just used the border element, and specified multiple things. The order determines what is assigned to what.

border-right: 2px dotted blue
is the equivalent to
border-right-width: 2px;
border-right-color: blue;
border-right-style: dotted;

It’s usually cleaner to write thing out, but that can be cumbersome. Try to find a balance, and use your best judgment.

Let’s now remove the borders, and add some formatting to the entire page.

html
{
  color: white;
  background-color: black;
}

#header
{
  text-align: center;
}

#menu
{
  float: left;
}

#article
{
  float: right;
}

Code to the tag affects everything on the page. Traditionally, the code used would have been for the tag, but with an XML declaration, that does not work the same.

The CSS attributes:
color – text color. We’ve changed it to white
background-color – obviously, the background color. We’ve changed it to black.

We see that the article section is too far to the right, now. Also, we probably don’t want things so close to the edge of the screen at all. We need that marginalized. Let’s remove the float attribute from article, and instead use margins to organize.

html
{
  background-color: black;
  color: white;
}

#header
{
  text-align: center;
  margin-left: 150px;
  margin-right: 150px;
  
  border-bottom: 1px dashed white;
}

#main
{
  margin-left: 150px;
  margin-right: 150px;
  border-bottom: 1px dashed white;
}

#menu
{
  float: left;
  width: 150px;

  margin-left: 25px;
  margin-right: 50px;
}

#article
{
  margin-left: 221px;
  margin-right: 50px;

  border-left: 1px dashed white;
}

Make these updates and refresh your page. There’s much more of a structure now, though all we’ve added were margins and borders. A margin is a space that pushes from left to right, or top to down. If you add a margin-left: 10px value to an element, it will be pushed to the right by 10 pixels. If you add a margin-right: 10px, anything to the right of the element will be pushed 10 pixels (as opposed to that element being pushed left).

Even when there’s hardly any data, though, you don’t want things all crampt. We’ll resolve this using height and min-height attributes.

#header
{
  text-align: center;
  margin-left: 150px;
  margin-right: 150px;
  height: 100px;
  
  border-bottom: 1px dashed white;
}

#main
{
  margin-left: 150px;
  margin-right: 150px;
  border-bottom: 1px dashed white;
  
  min-height: 600px;
}

#menu
{
  float: left;
  width: 150px;

  margin-left: 25px;
  margin-right: 50px;
  
  height: 100%;
}

#article
{
  margin-left: 221px;
  margin-right: 50px;
  
  min-height: 575px;

  border-left: 1px dashed white;
}

height is obviously the height of the element–how tall something is.
min-height specifies the height that the element must be at the minimum.

Keep in mind that percentage heights, such as height: 100%; in the menu element, can be the source of browser incompatibility between Firefox and Internet Explorer as they interpret this differently.

We’ll now touch up the layout with padding, and modifying the fonts.

h1
{
  font-size: 2em;
}

#header
{
  text-align: center;
  font-family: courier new;
  font-weight: bold;

  margin-left: 150px;
  margin-right: 150px;
  height: 100px;
  margin-bottom: 25px;
  border-bottom: 1px dashed white;
}

#main
{
  min-height: 600px;
  margin-left: 150px;
  margin-right: 150px;

  padding-bottom: 25px;

  border-bottom: 1px dashed white;
}

#menu
{
  float: left;
  width: 150px;
  padding: 10px;
  padding-top: 0px;
  margin-left: 25px;
  margin-right: 50px;
  
  font-size: .8em;
  font-weight: bold;
  height: 100%;
}

#article
{
  margin-left: 221px;
  margin-right: 50px;
  padding: 25px;
  padding-top: 0px;
  min-height: 575px;
  border-left: 1px dashed white;
}

Make these changes and refresh to see something you wouldn’t be too surprised to see for a web-site layout. The best designs are often rather simple. Admittedly, I am not a good visual designer, so you’ll probably want to look elsewhere for much advice in that department.

Padding is like a margin, except on the inside of an element. Where margins push outward, padding pushses inward, keeping text inside an element away from the edges.

Text (fonts) are formatted with font. font-family denotes the name of the font, such as Times New Roman, Courier, etc. Be careful about selecting a font, because the user can only view fonts he has on his own computer, so the list is limited. Here are some web-safe fonts:

Arial
Comic Sans MS
Courier New
Georgia
Lucida Sans
Times New Roman
Trebuchet MS
Verdana

Note that dingbat fonts (non-standard characters), such as Wingdings and Webdings, are not only not web-safe, they aren’t browser safe (Firefox does not display these fonts).

Also see that we’ve defined some font sizes
font-size: 2em

em is a scalable unit size, which means it changes based on the user’s configuration so that, for example, text doesn’t get too tiny on high resolution screens, or too large on low-res ones. This is a good method of assigning font sizes, but can be problematic in terms of layout sizes such as our menu, which we’ve defined as 150px wide.

That’s the end of our look at CSS, but it won’t be the last we use it. CSS is integral to web design.

In Part 3 we’ll look at linking to multiple pages and menu design.

Blog at WordPress.com.