Developers Guide To Multiplayer Games Wordware Game Developers Library Andrew Mulholland Instant Download
Developers Guide To Multiplayer Games Wordware Game Developers Library Andrew Mulholland Instant Download
https://ebookbell.com/product/developers-guide-to-multiplayer-
games-wordware-game-developers-library-andrew-mulholland-2140102
https://ebookbell.com/product/developers-guide-to-microsoft-
prism-4-building-modular-mvvm-applications-with-windows-presentation-
foundation-and-microsoft-silverlight-1st-edition-bob-brumfield-2120280
https://ebookbell.com/product/developers-guide-to-collections-in-
microsoft-net-calvin-janes-2371386
https://ebookbell.com/product/developers-guide-to-web-application-
security-michael-cross-4099920
https://ebookbell.com/product/developers-guide-to-microsoft-
enterprise-library-visual-basic-edition-visual-basic-ed-alex-
homer-5399156
Developers Guide To Microsoft Prism 4 Building Modular Mvvm
Applications Using Windows Presentation Foundation And Microsoft
Silverlight Bob Brumfield Geoff Cox David Hill Brian Noyes Michael
Puleio Karl Shifflett
https://ebookbell.com/product/developers-guide-to-microsoft-
prism-4-building-modular-mvvm-applications-using-windows-presentation-
foundation-and-microsoft-silverlight-bob-brumfield-geoff-cox-david-
hill-brian-noyes-michael-puleio-karl-shifflett-43034582
https://ebookbell.com/product/developers-guide-to-microsoft-
enterprise-library-alex-homer-nicolas-botto-bob-brumfield-grigori-
melnik-erik-renaud-fernando-simonazzi-chris-tavares-43149494
https://ebookbell.com/product/developers-guide-to-microsoft-
enterprise-library-alex-homer-nicolas-botto-bob-brumfield-grigori-
melnik-erik-renaud-fernando-simonazzi-chris-tavares-43142114
https://ebookbell.com/product/developers-guide-to-microsoft-
enterprise-library-2nd-edition-dominic-betts-julian-dominguez-alex-
homer-hernan-de-lahitte-grigori-melnik-fernando-simonazzi-mani-
subramanian-dominic-betts-12349076
Developer’s Guide to
Multiplayer Games
Andrew Mulholland
and
Teijo Hakala
Mulholland, Andrew.
Developer’s guide to multiplayer games / by Andrew Mulholland and Teijo Hakala.
p. cm.
ISBN 1-55622-868-6 (pbk.)
1. Computer games--Programming. I. Hakala, Teijo. II. Title.
ISBN 1-55622-868-6
10 9 8 7 6 5 4 3 2 1
0109
All inquiries for volume purchases of this book should be addressed to Wordware Publishing, Inc., at the above
address. Telephone inquiries may be made by calling:
(972) 423-0090
Contents
Theory Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 1
iii
Contents
iv
Contents
v
Contents
vi
Contents
vii
Contents
viii
Contents
ix
Contents
x
Contents
xi
Contents
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
xii
Introduction
With Internet technology developing rapidly, Internet gaming has become ever
more popular, while documentation on how to actually make Internet games
remains inadequate. Developer’s Guide to Multiplayer Games provides in-depth
coverage of all the major topics associated with online game programming, as
well as giving you easy-to-follow, step-by-step tutorials on how to create your
own fully functional network library, back-end MySQL database, and complete,
working online game!
The book contains two main areas. The first is dedicated to explaining practical
theory on how to utilize MySQL, Perl, sockets, and basic Windows dialog pro-
gramming. The second section consists of five extensive tutorials, leading you
through the stages of creating a working online game that you can both learn
from and expand upon.
After reading this book, you will have a solid knowledge of online game pro-
gramming and you will also be able to start making your own online games.
Also note that the companion CD-ROM contains all the source code from the
book and a ready-to-use version of the network library you will create in the
tutorial section.
We hope you enjoy reading and learning from this book as much as we have
enjoyed writing it!
xiii
About the Authors
Andrew Mulholland
Teijo Hakala
xiv
Theory Introduction
The theory section of this book is full of practical information that will help you
understand how to make functional online games. We recommend that you read
this section thoroughly before attempting the tutorial section, as there is a lot of
knowledge that will benefit you here.
This section first covers the basics of dialog-based Windows programming,
which we will utilize in the tutorial section to create our login and lobby system
for the sample online game. Then we cover how to use MySQL and Perl to create
a back-end database for your game, allowing you to interact with game data
directly from a web browser. Then we give an introduction to TCP/IP and sockets,
followed by how to get started with sockets programming. Finally, we learn about
different ways to send data, and how to modify the behavior of our sockets.
First, let’s look at how to create dialog-based Windows applications…
1
Chapter 1
Creating Windows
Applications in
Visual Studio
Introduction
The most essential knowledge anyone can have is the basics. If you already know
how to create dialog-based Windows applications, skip past this chapter. If not,
this chapter will give you a quick and easy introduction to it so that you will find
the rest of this book more accessible.
The reason for learning this is to be able to create our server applications for
the Microsoft Windows operating system.
3
4 Chapter 1 / Creating Windows Applications in Visual Studio
added to the queue and is then sent to the appropriate window to inform it that the
button has been pressed.
When the operating system creates a window, the window continually checks
for messages being sent to it. If it receives a relevant message, it will react
accordingly; otherwise, it will send it back to the operating system to be
reprocessed.
Each window created is assigned a unique handle that is used to control and
determine which messages are relevant to that window. In code, this is defined as
the HWND, or window handle. The main reason behind this system is to allow for
multi-tasking and multithreading. This means that the operating system can run
more than one application in one instance, even though a processor can only han-
dle one task at a time.
There is a lot more to windows than this, but this should give you a reasonable
overview of how the system works.
Creating a Window
Load Microsoft Visual Studio and select File, New…
The following dialog box should now be visible in the center of the screen.
Figure 1-1
Select the Projects tab at the top of the dialog and then choose the Win32 Applica-
tion option on the main display. Select the location for your project, enter your
project’s name, and click OK.
Chapter 1 / Creating Windows Applications in Visual Studio 5
Next, select the type of project you wish to create. Leave it on the default
option (An empty project) and click the Finish button. A project information box
appears; simply click OK in this box.
Now we are working with the Visual Studio main interface. Currently,
ClassView is active, but we are interested in FileView so select this tab.
Figure 1-2
FileView lists all of the C and C++ source and header files that are active in your
project. Currently we do not have any files in our project so we need to add our
main C++ source file.
Select File, New… as you did before, but this time select the Files tab instead
of Projects. The following dialog will be visible.
Figure 1-3
Select C++ Source File as shown in Figure 1-3 and type in the filename as
main.cpp. Click the OK button to add this empty file to your project.
You now have your main source file in your project, and it is visible in the
Visual Studio editor.
There are two main items required in a standard Windows program: the entry
point to your program, which is named WinMain, and the Windows callback proce-
dure (commonly named WndProc), which is used to keep your Windows
application up to date.
For what we require though, it is best to take the dialog approach, making it
even simpler to design and code. First, we need to add our dialog. Click File,
6 Chapter 1 / Creating Windows Applications in Visual Studio
New… again, but this time select Resource Script. Type in the filename as
resource and click OK.
Once this is done, you will notice another tab has appeared between the
ClassView and FileView tabs. This tab is called ResourceView and allows you to
visually create and edit dialogs for use within your program.
Figure 1-4
Once you select the ResourceView tab, you will be presented with the resource
editor. Right-click on resource.rc in the main view and then left-click on the Insert
option. You will then be presented with the Insert Resource dialog box.
Figure 1-5
Select Dialog and click New. Now you will see a sample dialog box in front of you.
For now, we will not do much to it except change the name of the title bar and its
identifier that I will explain after the code below.
Double-click on the sample dialog box that Visual Studio created. Now a dialog
properties box can be seen. All we are interested in here is the ID, which will
probably be set to Idd_Dialog1, and the Caption, which should be Dialog. Let’s
change the ID to Idd_Client and the Caption to Window Example.
OK, now it’s time to go back and do some code. We have our dialog template
that we can call from our code so let’s use it. Here is the code required to make
your dialog appear on the screen:
// Simple Windows Code
#include <windows.h>
#include "resource.h"
LRESULT CALLBACK
ClientDlgProc(HWND DialogWindow, UINT Message, WPARAM wParam, LPARAM lParam)
{
// Process Messages
Chapter 1 / Creating Windows Applications in Visual Studio 7
switch(Message)
{
case WM_INITDIALOG:
return FALSE;
case WM_COMMAND:
switch(wParam)
{
case IDCANCEL:
EndDialog(DialogWindow, FALSE);
return FALSE;
default:
break;
}
break;
default:
break;
}
return FALSE;
}
int APIENTRY
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
DialogBox((HINSTANCE) hInstance, MAKEINTRESOURCE(IDD_CLIENT), NULL,
(DLGPROC) ClientDlgProc);
return 0;
}
The OK button on the dialog can be pressed but will have no action, whereas the
Cancel button will close the dialog.
NOTE If you get an error and it tells you it can’t find afxres.h, you need to install
MFC support for Visual Studio, which comes with the Visual Studio package.
If you have never seen Windows code before, the code above may look complex
and a little confusing. Welcome to the world of Windows! It’s not that bad, honest.
Let’s start with the WinMain function. This is simply the point at which Win-
dows starts executing your code. Do not worry about the variables that are passed
in; they are controlled by Windows and are beyond the scope of this book.
The main issue here is the DialogBox function and callback procedure
(ClientDlgProc) that creates our dialog window on the screen. The first parameter
is the instance of the application that you simply take from the first parameter of
the WinMain function. Next is the identifier that we set when we created the
8 Chapter 1 / Creating Windows Applications in Visual Studio
The dialog box shown in Figure 1-7 will now be visible on the screen. All we need
to change here is the ID. Change the text Idc_Static to Idc_Serverstatus. This will
give it more meaning when it comes to adding it into the code.
Chapter 1 / Creating Windows Applications in Visual Studio 9
Figure 1-7
Now we have some text, and we want to be able to set it to a value from within
our code. For example, if we want the text to read “Server Online,” add the fol-
lowing lines of code after the line that contains “case WM_INITDIALOG”:
SendDlgItemMessage(DialogWindow,IDC_SERVERSTATUS, WM_SETTEXT,NULL,(long)"Server
Online");
Therefore, when the dialog box is initialized, Windows will send a message to the
dialog box to tell it to update the Idc_Serverstatus text with the string you sup-
plied in the function. In this case, it would update the text from “Static” to
“Server Online.”
The first parameter is the handle to the dialog, which is the first variable that
is passed into the dialog update procedure. The second is the identifier for what
you want to change or update. Next comes the command that you wish to send.
There are many commands and the best way to figure out how they work is just
to experiment with them. For now we are using WM_SETTEXT, which tells
Windows to change a static text string in a dialog box. The fourth parameter is
not used for the WM_SETTEXT command so we simply set it to NULL. The
final parameter is used to declare the string with which we want to update the
static text, in this case “Server Online.” Also, note that the string must be type-
cast to a long.
TIP Also try experimenting with editable text. It works on the same principles dis-
cussed above, and you simply send a WM_GETTEXT message to retrieve what the
user entered.
a program, rather just a collection of functions that we can use from within our
programs. The library is created using standard C/C++ source and header files,
but the output is a library rather than a Windows executable.
When you compile your library, the compiler will generate a library file with
the extension .lib. To use the functions in your library, you are required to include
it in your project and include the header file that was used to create the library
(which contains all the external variables, types, and function prototypes).
The easiest way to use your library is to create Lib and Include folders for your
library and include those directories in the Visual Studio directory settings that
are explained in the tutorial to follow.
n Examples All example programs that display how to use your library are
stored in this folder. This is probably one of the most useful things that can
accompany your library since the source code is not visible to any other pro-
grammer using it.
n Formats This is where you store any file formats specific to your static link
library (i.e., your own 3D model format).
n Include This stores the entire collection of C/C++ header files that are
needed to use your library. This is one of the directories that you must set up
in Visual Studio to make your library work.
n Lib This is where you actually store your complete library file and the other
directory required by Visual Studio. It is a good idea to include both the
release and debug versions of your library here so that it is possible to debug
and create final release applications with the libraries.
n Source All source code related to your library must be kept in this folder.
n Tools Any programming tools that are used alongside your library are stored
here (such as file format converters).
Chapter 1 / Creating Windows Applications in Visual Studio 11
Now that we have our structure, we need to create a static link library project.
This is done by selecting File, New… in Visual Studio. The dialog box in Figure
1-9 should now be visible.
Figure 1-9
Select the Win32 Static Library option and enter a name for your library. Next,
select the location and press the OK button.
In the dialog box that appears, leave both the Pre-Compiled header and MFC
support options unchecked as we will not be using either in this book, and click
Finish. A project information box is now visible, but simply click OK here.
Next, we need to add our source and header files to the project as you did
when creating the window. Remember that this time we do not require the
WinMain or Update procedure, just functions that we wish to reuse. Let’s call the
source file library.cpp and the header file library.h for this example.
If you now press F7, it will build your library and put it in the Release or
Debug folder depending on your project configuration. The library will have the
same name as your project. For example, if your project is named gamephysics,
your library will be named gamephysics.lib.
It is a good idea to make Visual Studio automatically copy your header file and
library to the correct directories in your structure to assure that you are always
using the latest version. Selecting Project, Settings from the main menu makes
the dialog box in Figure 1-10 (shown on the following page) visible.
Set the Output file name for your library to whatever you wish to call your
library and choose where you want it to go relative to the directory your source
files are in. This must be done for both release and debug configurations. In the
previous dialog the debug settings are currently active.
12 Chapter 1 / Creating Windows Applications in Visual Studio
Figure 1-10
TIP It is a good idea to have both debug and release versions of your library. Call
your release version the correct name (i.e., GamePhysics.lib) and add a suffix to
the debug version (i.e., GamePhysicsDebug.lib) to distinguish them easily.
Now the library file is created in the correct directory in our structure when the
project is built. We also want to copy our header file to the Include directory of our
structure.
As can be seen in Figure 1-11, you simply add a Post-build command that tells
the compiler to copy the header file(s) to the Include directory.
Figure 1-11
Chapter 1 / Creating Windows Applications in Visual Studio 13
We have now covered the basics on how to create a static link library. The most
important thing to remember is to prototype all functions and make all the global
variables external that you wish to be accessible outside of your library. In the
next section, we will discuss how to set up Visual Studio to find your library.
Figure 1-12
You must now add the Include directory of your library for the Include files and
the Lib directory for the Library files. You select which one you wish to add by
changing the top-right pull-down box.
Now Visual Studio is able to find and recognize your static link library. To use
it in a program you have written, you must first load your project into Visual
Studio, then select Project, Settings...
Next, select the Link tab and add your library name before kernel32.lib. Also,
remember to include the header file for your library in your main code.
14 Chapter 1 / Creating Windows Applications in Visual Studio
Final Notes
Here we have provided the basics of creating dialog-based applications in Visual
Studio. The best thing to do is experiment by creating dialogs, adding buttons, and
making the buttons set strings to different values when you press them. Also,
learn to use editable text as this is highly useful and allows the user to put feed-
back into your program.
If you are interested in learning more, there are entire books written on Win-
dows programming and there is also an excellent resource available on the
Internet (http://msdn.microsoft.com), but the quick introduction provided here
will give you enough knowledge to understand the concepts used in this book.
Internet-Based
Database Systems
Introduction
This chapter covers how to create a stable and fast database system for your game
server. In later chapters you will find out about ways to access it from sockets and
the Internet.
Although it is possible to store player information on the player’s local
machine, in reality it makes much more sense to store the data on the server for
many reasons. The first and most important reason is to avoid players running
“hacks” on their computer to change their character data in the game or even
backing the data up to another file. If the data is stored on the server, it makes it
impossible for the player to run a local game hack that will modify the character
data. Another reason for this is to allow players to play from different locations and
machines without having to copy their character data to another computer.
First, we will cover the installation of MySQL, an excellent, stable, and free
database system, on both the Linux and Windows operating systems.
15
16 Chapter 2 / Internet-Based Database Systems
Installing MySQL
Linux Specific
First, you need to install a version of the Linux operating system and set up the
Apache web server as well as Perl 5. If you do not already have a copy of Linux,
we would recommend Red Hat version 6.2 or greater (http://www.redhat.com/).
Next, you need to download the file mysql-3.23.36-pc-linux-gnu-i686.tar.gz (a
newer version may be available but this chapter is based on this version) from
http://www.mysql.com/Downloads/MySQL-3.23/mysql-3.23.36-pc-linux-gnu-
i686.tar.gz or simply copy it off the CD-ROM supplied with the book.
Once you have this file, if it is not already on your Linux machine/server, you
need to upload it. When working with Linux, ensure that you are logged in as the
root user or some of the topics covered in this chapter may not work correctly. It
does not matter where you place this file on your Linux machine as long as you
keep a note of where it is.
Go to Linux and change to the directory to which you copied or uploaded the
file. Next, you need to enter the following list of commands to unpack and install
MySQL:
shell> groupadd mysql
shell> useradd -g mysql mysql
shell> cd /usr/local
shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -
shell> ln -s mysql-VERSION-OS mysql
shell> cd mysql
shell> scripts/mysql_install_db
shell> chown -R mysql /usr/local/mysql
shell> chgrp -R mysql /usr/local/mysql
shell> bin/safe_mysqld --user=mysql &
That’s all there is to installing MySQL on Linux. The last command you entered
started the MySQL daemon that controls all the connections to your database and
all the operations you are going to perform on it.
For the next part, you want to be able to access the MySQL console. To do
this, type the following from the /usr/local/mysql directory:
shell> ./bin/mysql
Chapter 2 / Internet-Based Database Systems 17
Windows Specific
Assuming you have a working version of Microsoft Windows 9x/NT on your com-
puter, you first need to download from http://www.mysql.com/Downloads/
MySQL-3.23/mysql-3.23.36-win.zip or copy from the companion CD the
mysql-3.23.36-win.zip file.
Unzip the file to a temporary folder (i.e., C:\temp\mySQL) using a program
such as WinZip (http://www.winzip.com). (There is an evaluation version of
WinZip on the CD-ROM.)
Next, go to the temporary directory where you extracted the files and double-
click on setup.exe to begin the MySQL setup program.
Follow the simple installation through; select the directory you wish to install
to, then just select the typical installation option and MySQL will be installed to
your computer.
Finally, you need to be able to access the MySQL console. To do this, go to the
directory in which you installed MySQL and then go into the bin directory. The
MySQL daemon will automatically be running so simply double-click on
MySQL.exe to bring up the console window.
The console window should appear as shown in Figure 2-1.
Figure 2-1
NOTE If for some reason the MySQL daemon is not running, you will want to be
able to start it manually. To do this go to the directory which you installed
MySQL into, and then go into the bin directory. Here you will find a file called
mysqld.exe. Double-click this file to start the MySQL daemon running. If you are
running Windows NT, use the mysqld-nt.exe file instead. Also, if you wish the
daemon to start every time you load Windows, simply add it to your start up
folder in your Start menu.
18 Chapter 2 / Internet-Based Database Systems
Overview of MySQL
SQL is an acronym for structured query language. This means it accepts com-
mands in an easy to understand and structured format. We will be using the
console mode on MySQL to create our databases and tables that are contained
within it. Later in this chapter we are going to cover how to access them from
outside the console.
A database is structured as shown in Figure 2-2. You have several records of
data per table and several tables per database.
Figure 2-2
The first thing we need to do is create the database, as it is the foundation of the
complete system.
If everything has gone according to plan, it will inform you that the query was OK
and that one row was affected.
We now have our database in the system. We can view all the databases that
have been created in MySQL by typing the following command:
mysql> SHOW DATABASES;
Chapter 2 / Internet-Based Database Systems 19
The console should now display a list of database names that are on the system;
you should also see your gamedata database there. Figure 2-3 shows what the
console should be displaying.
Figure 2-3
The final thing we must do is select which database we wish to work with. This is
done with the following command:
mysql> USE gamedata;
Now we will move on to how to add your tables into the database.
on relational databases). First we must make sure we are using the gamedata data-
base that we created previously. To make sure of this, type the following
command:
mysql> USE gamedata;
Now that is done, we can enter the following command to create our database that
we will call playerinfo. Note that it is fine to use the Return key to make it clearer
as the statement will only end when you add the semicolon.
mysql> CREATE TABLE playerinfo (
mysql> id INT AUTO_INCREMENT,
mysql> name VARCHAR(30),
mysql> xpos INT,
mysql> ypos INT,
mysql> exp INT,
mysql> PRIMARY KEY(id));
This command will create the playerinfo table that can hold our information and
give it a unique identifier that will automatically increment every time a new
record of data is added into the table.
The Primary_Key() command is used to optimize the database for searching
for a particular variable in a table. Since we will be looking for the ID of a player
most, it makes sense to set this to the primary key for the table.
Next, it is a good idea to check that your table has been created correctly. It is
easy to correct a mistake at this stage, but becomes much more difficult once you
start adding data and using the system.
To check that our table now exists in the database, we want to use the follow-
ing command:
mysql> SHOW TABLES;
Chapter 2 / Internet-Based Database Systems 21
When you press Return, the following console screen should now be visible.
Figure 2-5
As you can see from the preceding figure, MySQL tells us that there is only one
table in the gamedata database now, which is our playerinfo table. More tables can
be added to the database, as we will see later in the relational databases section.
Another useful command is the Describe command, which allows us to see all
the data in a table. This command can be used to check that our table was created
the way we wanted it to be. The command is called as follows:
mysql> DESCRIBE playerinfo;
Once you press Return, the following will be displayed on the MySQL console.
Figure 2-6
As you can see from this screen, the first column denotes the names of the
fields we entered — id, name, xpos, ypos, and exp. The next column tells us the
type. This is the one we should check carefully as the database will obviously not
work as you would hope if you try to place a string into integer storage. Take note
22 Chapter 2 / Internet-Based Database Systems
also that the id field is never NULL as it will always be automatically assigned a
unique integer value by MySQL every time data is added to the table. The final
column specifies any special cases you have assigned to the fields; in this case, we
have asked the id field to be assigned a unique number so auto_increment appears
in this column.
That’s all there is to adding standalone tables that do not interact with each
other. We will find out later in this chapter how to add tables that interact with
each other using the unique ID system. Next, however, we will cover how to add
data into the table we have created from the MySQL console and also from differ-
ent types of files.
To insert this into our table we would use the following syntax:
mysql> INSERT INTO playerinfo VALUES
mysql> (NULL,’Jeff Henderson’,14,35,1431);
Notice that the first data we enter into the table is a NULL. This is to tell MySQL
to automatically assign that data. Since we also have an Auto_Increment setup for
the first column of data, it will automatically change that NULL into a unique inte-
ger for the data we are entering. The rest is straightforward; first, we tell MySQL
what table we wish to insert data into (in this case, playerinfo), followed by the
values we wish to insert into the table. We can also add more than one segment of
information at once by simply placing a comma after each complete set of data.
Let’s assume we want to add another three players into the database and their
information is as follows:
Name: Sandra Smith
X Position: 21
Y Position: 86
Experience: 4563
Figure 2-8
24 Chapter 2 / Internet-Based Database Systems
If everything has gone according to plan, we should now have four records of data
in our playerinfo table in the gamedata database.
This selects all the fields and records from our playerinfo table. Therefore, the
output from the console should contain four records of information and display all
the data from each of the records. Figure 2-9 shows the expected output.
Figure 2-9
As you can see from the figure, all the data has been entered into the table cor-
rectly. Also, note how the id field has been incremented automatically for each
record as we intended.
Let’s now say we only want to display the name and experience data. Again,
we want all the records, but we only want to select the correct fields, which in this
case are name and exp. To do this we would again use the Select command, but
instead of using the “*” wildcard, we specify the fields we wish to display.
mysql> SELECT name,exp FROM playerinfo;
Chapter 2 / Internet-Based Database Systems 25
The preceding command will select all the name and experience fields from the
playerinfo table. Therefore, our expected output will be a four-row list of names
and experience levels. This should look as follows.
Figure 2-10
As we mentioned before, we can also use a Where command after Select, to add
conditions the data must satisfy before it is selected. Let’s say for example, we
only wanted to see the players that had more that 1,000 experience points. We
would use the following statement to retrieve this information from the table:
mysql> SELECT * FROM playerinfo WHERE exp > 1000;
When we execute this command by pressing Enter, MySQL will attempt to select
all the data for the players that have an experience level greater than 1,000. This
means that only Jeff, Sandra and Jennifer should be visible. Figure 2-11 shows the
expected output.
Figure 2-11
26 Chapter 2 / Internet-Based Database Systems
As well as comparing if a value is greater than a given number, we can also check
if it is less than or simply equal to it. Let’s get the player’s ID and name from the
table if his or her y position is equal to 86. We would use the following command
to do this:
mysql> SELECT id,name FROM playerinfo WHERE ypos = 86;
As Sandra Smith is the only player with a y position of 86, she is the only person
who should now be displayed in the console. We should only be able to see her ID
and name as that is all we asked to select from the table. Figure 2-12 shows the
expected output.
Figure 2-12
Figure 2-13 shows what will happen when we execute the command. As you can
see, the id and coordinates for John Brooke are now visible.
Chapter 2 / Internet-Based Database Systems 27
Figure 2-13
The other method is to use the MySQL Like command that allows you, for exam-
ple, to select all names starting with a specific letter. If we wanted to select all the
players from the table whose names started with the letter “J,” we would use the
following syntax:
mysql> SELECT * FROM playerinfo WHERE name LIKE “J%”;
When executed, this command would produce the following output on the console.
Figure 2-14
As you can see from the command, the “J%” tells MySQL to select all the names
starting with “J.” The percentage sign in this case is used as a wildcard and can be
used in many combinations to produce useful results. Another example of the Like
command would be to select any name (string) that contains a certain letter or
phrase.
Let’s try to select any name that contains the letter “S” anywhere, not just the
start. To do this we would simply place the wildcard (%) at either side of the letter,
28 Chapter 2 / Internet-Based Database Systems
making the location where it finds the letter irrelevant. We would therefore use
the following command to accomplish this:
mysql> SELECT * FROM playerinfo WHERE name LIKE “%S%”;
The only name which does not contain the letter “S” is John Brooke, so the other
three names should be visible as shown here.
Figure 2-15
Here is how it would look when we execute it from the MySQL console.
Figure 2-16
Chapter 2 / Internet-Based Database Systems 29
Now, if we use the Describe command on the playerinfo table, we notice that the
lastlogin field has been added to the end of the table. To describe the table we use
the following command:
mysql> DESCRIBE playerinfo;
When we execute this, we should see the output from the console as shown in
Figure 2-17. Note the new row at the end, which is our new timestamp field.
Figure 2-17
We can also use the Alter command to change the data type of a field. Let’s say we
have decided to allow the players to have 50 characters in their name instead of
the 30 we allocated when we first created the table. To accomplish this we again
use the Alter command, but instead of Add we use the Modify command as shown
here:
mysql> ALTER TABLE playerinfo MODIFY name VARCHAR(50);
When we execute the command in the console, we should see that our four rows
of data have been affected. The data has not actually changed, although the stor-
age space for the field has. Figure 2-18 shows the expected console output.
Figure 2-18
30 Chapter 2 / Internet-Based Database Systems
We can again describe the table to check that our changes have gone as planned.
Figure 2-19 shows the expected console output from the Describe command.
Figure 2-19
As you can see from the console output, the type for the name field is varchar(50)
instead of our original varchar(30).
A timestamp is a single large integer that represents the date and time. The first
four digits represent the year. The next two represent the month and the two after
that represent the day of the month. The next four digits are for the time in 24-
hour format. The final two digits represent the seconds. Figure 2-21 shows a
summary.
Figure 2-21
The reasoning for this structure is to allow for easy comparison with other
timestamps and easy storage in the database. With this method of storage, it is
simple to use basic integer comparisons, such as greater than or less than, to find
out if a timestamp is before or after another timestamp or a specific date and/or
time. Another feature of the timestamps is if you specify the data in MySQL as
NULL for a timestamp, MySQL automatically places the system date and time in
the database, which can be very useful to us, as you will see in the example to
follow.
Now that we have our timestamp field in our table, let’s try updating the values
in our four existing entries. To update information in a table, we use the MySQL
Update command. Now we will update Jeff Henderson’s timestamp to be the cur-
rent system time. Simply updating the timestamp field with NULL does this. The
syntax for this function is:
mysql> UPDATE playerinfo SET lastlogin = NULL WHERE name = “Jeff Henderson”;
First we will tell MySQL that we wish to update a table. Then we specify the
table name, which in this case is our playerinfo table. Then we must tell it what to
update. Here we tell it to set the lastlogin field to NULL (which means set it to
the current date and time). If we excluded the Where from the end of the com-
mand, it would simply update all the lastlogin fields for all the entries (records) in
the table. So we want to specify which record we wish to update, which in this
case is Jeff Henderson’s record. When we execute the command, we should see
that one row was found and one row was changed. You can see the expected out-
put in Figure 2-22.
32 Chapter 2 / Internet-Based Database Systems
Figure 2-22
Now, when we select all the data from the table, we notice that Jeff Henderson’s
lastlogin date and time has been set to the time when we executed the command.
See Figure 2-23 for the expected output.
Figure 2-23
In addition to automatically setting the date and time with MySQL, we can manu-
ally set it simply by inputting the correct integer, as long as we ensure it is in the
correct format. Let’s manually set Sandra Smith’s lastlogin date to the following:
14th March 1999 at 3:35pm (and no seconds)
To do this, we again use the Update command, but we do not set the timestamp to
NULL. The integers we require for this are as follows:
Year: 2001
Month: 03
Day: 14
Hour: 15
Minutes: 35
Chapter 2 / Internet-Based Database Systems 33
Seconds: 00
Therefore, our integer is: 20010314153500. We then put this into the command as
follows:
mysql> UPDATE playerinfo SET lastlogin = “20010314153500”
WHERE name = “Sandra Smith”;
Our expected output from the execution of this command can be seen in Figure
2-24. Notice that one row (record) was matched and changed.
Figure 2-24
This time when we select all the records from the table, we can see that Sandra’s
information has been updated to the date and time we specified. See the expected
output in Figure 2-25.
Figure 2-25
Note that when you are updating information in a table, you can use any of the
Where cases that we have discussed before in the chapter, so we could, for
34 Chapter 2 / Internet-Based Database Systems
example, set all the experience levels to 1,000 for people whose names start with
“J” like this:
mysql> UPDATE playerinfo SET exp = 1000 WHERE name LIKE “J%”;
When executed, this command will update all the players with a name starting
with “J” and set their experience levels to 1,000. In our table, we have three play-
ers whose names start with “J,” so you can see from Figure 2-26 that there are
three matching rows (records) and that three were changed (updated).
Figure 2-26
Now, if we select the data, you will see in Figure 2-27 that Jeff, John, and Jennifer
all have an experience level of 1,000.
Figure 2-27
It is also possible to check more than one field when updating or selecting infor-
mation from a table. For example, if you wanted to display the information of all
the players whose x coordinate lies between the values of 10 and 20, you would
use the following command:
Chapter 2 / Internet-Based Database Systems 35
mysql> SELECT * FROM playerinfo WHERE xpos > 10 AND xpos < 20;
We can also use this method with the Update command. If we wanted to set the
experience level to 500 for all the players with an x coordinate greater than 10 and
less than 20, we would use the following command:
mysql> UPDATE playerinfo SET exp = 500 WHERE xpos > 10 AND xpos < 20;
When we execute this command, we will see that two rows (records) have been
updated. This can be seen in Figure 2-28.
Figure 2-28
The two records that were updated were Jeff’s and Jennifer’s. Their x coordinates
lie between the parameters we specified, hence they were updated with the new
information. The expected output can be seen in Figure 2-29. Notice Jeff’s and
Jennifer’s experience levels are now both set to 500.
Figure 2-29
Other documents randomly have
different content
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com