Limted Time Offer: Torque Engine for only $99!

Leave a comment Standard

Garage Games is back in action and is currently offering the Torque 2D/3D and Iphone/Ipad versions for only $99 each. What a steal for a piece of software that usually costs several thousand dollars!! Get it while the offer lasts… I did 🙂

PHP Tutorial: Connecting to a MySQL Database

Comment 1 Standard

You would think this is really obvious but I see a TON of posts on devnetwork.net (great php/mysql forum by the way) where people put their login and password for their database on every page from a non-protected directory. Yikes!! This is a big no-no!

So, here’s the low down on how to setup a connection to a MySQL database using PHP and make sure your login information is protected. First, you’ll need a database, PHP, and a place to host your files. Once you have those you’re ready to go. Don’t have a hosting provider? No problem, check out XAMPP.

1) You want your login for your database to be protected. That means you want the file to reside in a non-public part of your website. For instance, in most hosting places when you go to view all of your files you know to put them in the public_html folder or the www folder or the index folder. Your database login needs to be in the directory ABOVE your public folder. For most people this is called home, the name of your website, or even the root directory.

1) Create a file called dbconnect.php (or any other name that suits your fancy) in your home/root directory. That means if people navigate your website they’ll never be able to accidentally access this information because your home/root directory has different chmod permissions (711) then your public_html directory (750).

2) Now you need to write the code to make the actual connection to the database in dbconnect.php.

<?php
/**
* replace things with { } curly brackets with the appropriate information
* including the curly brackets! don't leave those in there...
**/

//connect to the server
mysql_connect("localhost", "{username}", "{password}")
     or die ('cannot connect to database because ' . mysql_error());

//select the database you're going to use
mysql_select_db ("{databasename}")
     or die ('cannot select this database because ' .  mysql_error());

?>

3) That’s it for the code to connect! Short and sweet. Now the question is how to get it in all your files.

4) Create a file in your public_html folder called dbconnect.php. You want this file to be publicly accessible to anyone. Put this inside of it:

<?php
/**
* include your database connection from a protected directory
* by include it from the directory above (../) where this file is
**/
include('../dbconnect.php');

//do all the rest of your usual php coding here
echo "connection successful!";

?>

If you don’t get an error message when you try to view this php script then you know your include was successful. Now there’s no chance someone can get the login and password for your database and you can access it from your php files like you normally would AND you don’t have to rewrite the connection statement at the top of EVERY php page you make.

Nifty huh?

XAMPP: Learn PHP & MySQL Without Online Hosting!!

Comment 1 Standard

One of the questions I get most frequently is what I use to make my SIM games. My answer is always the same, PHP and MySQL. Let’s say you wanted to learn these languages, so you find some tutorials and start reading. Only now you realize you need somewhere to practice what you’ve learned. Hosting can be expensive, especially for hosts that come with PHP/MySQL for someone who only wants to play around with the languages and isn’t looking to develop an entire website.

XAMPP is your solution. XAMPP is developed by Apache Friends and it will let you write and test PHP code as well as create and manging your own database. The best thing about it, its FREE!!

Go to this website: http://www.apachefriends.org/en/xampp.html and download XAMPP for your operating system. Once you’ve downloaded it run the installer (Windows machines) or follow the directions to get it setup (Linux machines).

Once you have it installed you’ll need to turn it on before you can use it. Navigate to the folder where you installed it. You’ll see two programs, one called XAMPP_START and the other called XAMPP_STOP. Every time you want to run XAMPP you need to click on XAMPP_START. Make sure you turn it off before you turn off the computer, otherwise you may get a startup error the next time you try to use it. It’s not going to keep XAMPP from working but its annoying (and has a really loud beeping noise).

Now that XAMPP is on you can make sure it installed correctly. Open a browser window (Internet Explorer, FireFox, Opera, Netscape, whatever you like most). In the address bar type in: http://localhost

One thing to understand here. You don’t have to be online for XAMPP to work. In fact that’s what makes it so powerful. Now you can test all your files and programs right from your computer at home even if you don’t have Internet access.

If you’ve installed XAMPP correctly you’ll see an orange and white screen that shows some demo programs. Take a look through them, there’s a few neat things. You’ll also see information about what’s currently running. One of the great things about XAMPP is that you can switch from php version 4 to php version 5. This is extremely useful for people who want to switch over scripts from one version to another. That way you can iron out any problems you have and fix them before you switch.

The next question is, where do you put your files to test things? Easy. Navigate to where you installed XAMPP. You’ll see a folder called htdocs. All of your php should go in that folder. For convience, its easier to make a folder called testing inside of htdocs because you’ll end up with a lot of stuff in there and all the demo programs are in there too.

So inside {XAMPP_install_path}/htdocs/testing you can now write and test your code! Let’s say you make a file called helloword.php inside of testing. That means it’s {XAMPP_install_path}/htdocs/testing/helloworld.php. To view this file open a browser window and type in: http://localhost/testing/helloword.php

Presto! Your php works!

But there’s one other thing that’s essential. MySQL. XAMPP comes with phpMyAdmin, which you may or may not be familiar with. It helps you setup all of your databases with a graphical interface. To get to it start XAMPP then go to http://localhost/phpmyadmin

So there you have it. Now you know how to get XAMPP, install it, start/stop it, add files so you can see them, and access phpMyAdmin to help you setup your databases.

And you didn’t need to pay for hosting 🙂

Now, are you ready to learn some PHP? Read our three part Learn PHP tutorial to get you started in the right direction. Try putting some of the example code into your helloworld.php file and see what happens.

AJAX Tutorial: Hangman Game (no database required)

Comments 6 Standard

Last year I made an PHP tutorial of an OOP Hangman game (no database required) for a Siminar I spoke at. This year as a part of my new Game Tutorial Series I’m adding a new tutorial to my collection. This tutorial will teach you how to modify the PHP hangman game we created and add some AJAX to it using jQuery so we don’t have to refresh the page every time we guess a new letter or start a new game. If you haven’t followed along with the original PHP tutorial I would strongly suggest you do as I won’t touch on anything introduced in the last one.

Download the Working Source Code
.zip archive

Getting jQuery

First thing is first we’ll need to get the jQuery library before we start updating any code. For those of you that don’t know, jQuery is code library that makes doing JavaScript quick and pretty painless. You can download or link to a copy offered on a Content Delivery Network (CDN) like Google Code. Personally I recommend downloading a copy if you’re going to post this game on a high traffic/visibility website. Sometimes if you link to a copy of jQuery on a CDN your site can experience lag and/or delays if the CDN is slow and your game won’t work at all if the CDN is down. On the other hand if you have a small website or limited space to store your files then there’s no need to download a copy of jQuery, linking to it is a better option. In this tutorial I’ve downloaded and included the jQuery file in the js folder of the .zip archive.

Setting Up For AJAX

Because we want our game to display using AJAX we need to create a new JavaScript file called hangman.js. This is what we’ll use to make all of our AJAX calls and respond to the player’s input.

Now that we have two JavaScript files we have to update our index.php file so it knows both of those JavaScript files are necessary to run the game. In the <head> tag, under the link to our stylesheet, we add two lines of code that tell our browser to load our JavaScript files:

<head>
        <title>Hangman</title>
        <link rel="stylesheet" type="text/css" href="inc/style.css" />
        <script language="Javascript" src="js/jquery-1.7.1.min.js"></script>
        <script language="Javascript" src="js/hangman.js"></script>
</head>

We also need to remove our $_SESSION[‘game’][‘hangman’] check from the top of our index file. Our AJAX calls will be running the game so it’s no longer necessary here. However we leave the session_start() at the top of the page so that if the player accidentally refreshes the page they don’t loose the game they had in progress.

Next we remove the code  inside of our <div id=”content”> and set that aside for later because we’ll need to use parts of it in our AJAX. In it’s place we’re going to enter a loading message. This is what the page will display before the AJAX calls have finished processing.

<body>
        <div id="content">
        <center>Loading Hangman.... please wait.</center>
        </div>
</body>

Writing the Hangman.js File

Now it’s time to jump into jQuery and AJAX.

$(document).ready(function() {

    //start the game when the page loads
    playGame();

});

jQuery uses a special function to check when the page has finished loading. Anything you put inside of this function will run as soon as the page is loaded, or in response to something someone has done on the page, like mouse clicks or using the keyboard. For this tutorial all we need it to do is call our AJAX function that will load and display the game to the content div on our index.php file.

/***
* Purpose: play hangman
* Preconditions: none
* Postconditions: new game has started or existing game is in play
***/
function playGame()
{
    $.ajax({
        url: 'ajax/index.php',
        data: {type: 'playGame'},
        success: function( data ) {
            $("#content").html(data);
        }
    });
}

Inside of our playGame() function we use AJAX to tell the browser to load our ajax file and send it some data (the type of action we’re doing, whether or not to start a new game, the letter the player guessed). Then we use a success callback function to load the results of our ajax call onto the page. A callback function is a function that runs as a result of being called by another process. In this case our callback function, success,  is loading the data we’ve retrieved through AJAX and putting it into the content div’s HTML property.

/***
* Purpose: guess a letter
* Preconditions: none
* Postconditions: game status updated
***/
function guessLetter()
{
    //make sure they've entered something into the box
    if (!$("#letter").val()) {
        alert("You must enter a letter.");
        return;
    }

    //check to make sure they've entered a letter
    if (!isLetter($("#letter").val())) {
        alert("This is not a letter. Please enter a letter.");

        //clear out the value in the input box
        $("#letter").val("");
        return;
    }

    //if it was a letter then submit the guess
    $.ajax({
        url: 'ajax/index.php',
        data: {type: 'playGame', letter: $("#letter").val()},
        success: function( data ) {
            $("#content").html(data);
        }
    });
}

/***
* Purpose: check to see if a value is a letter
* Preconditions: value to check
* Postconditions: returns true if this is a letter
***/
function isLetter(value)
{
    var lettersOnly = /^[a-zA-Z]+$/;

    //check to make sure there are no numbers and the value isn't more than 1 characters
    if(value.match(lettersOnly) && value.length == 1)
        return true;

    //otherwise this isn't a letter
    return false;
}

If we want to respond to someone trying to guess a letter we use a fairly similar process. Our guessLetter function checks to make sure the player has entered a value into our letter input box, then checks to make sure the value inside of it is really a letter, and finally uses an AJAX call to update the game by passing it the letter entered.

/***
* Purpose: start a brand new game
* Preconditions: none
* Postconditions: new game has started
***/
function newGame()
{
    $.ajax({
        url: 'ajax/index.php',
        data: {type: 'playGame', newgame: true},
        success: function( data ) {
            $("#content").html(data);
        }
    });
}

The last piece of our ajax file is the newGame function. When the game is over we want to make sure we use AJAX to update the game state and then refresh the page to a new game.

Writing the AJAX File

Now that our JavaScript file will send AJAX requests we need to write the file on the other end of the request — the file that responds to the data we’re sending it. Create a new folder and name is ajax. Inside of it make an index.php file. Inside of the file put the following:

<?php
//include the required OOP files
require_once('../oop/class.game.php');
require_once('../oop/class.hangman.php');

//this will keep the game data as they make a new ajax request
session_start();

//respond to AJAX requests
echo doAction($_GET);

function doAction($getdata)
{
    switch ($_GET['type'])
    {
        case "playGame":
            return playGame($getdata);
        default:
            return "Invalid option selected.";
    }
}

/***
* Purpose: Display and play the game
* Preconditions: a game exists
* Postconditions: the current game is displayed to the screen
***/
function playGame($getdata)
{    
    //if they haven't started a game yet let's load one
    if (!$_SESSION['game']['hangman'])
        $_SESSION['game']['hangman'] = new hangman();

    echo "<h2>Let's Play Hangman!</h2>";
    $_SESSION['game']['hangman']->playGame($getdata);
}

In this file we have two functions, doAction and playGame. Both functions take the $_GET data sent by our AJAX calls and do various things depending on the data sent to them. doAction is run every time this ajax file loads. It decides which function it needs to call, depending on the type we’ve sent it, and then returns the result to the screen.

Now pull up that code I had you set aside earlier. We’re going to move that into our playGame function with a few adjustments. We no longer need the <form> tags around our game data. In addition instead of sending $_POST data to our hangman object we’re now sending $_GET data.  The $_GET data contains the information we were previously posting from the <form> tags. Since AJAX is refreshing what appears inside of our content div there’s no reason to use our <form> and $_POST variables anymore.

Last But Not Least

We’re almost done! Before we can view our handy work we need to open our hangman OOP file. Anywhere we had a $_POST statement we need to change that to a $_GET since we’re no longer using the $_POST variable.

Finally,  we need to update our new game and guess buttons so they run the newGame and playGame javascript functions we wrote earlier:

<input type=\"text\" name=\"letter\" value=\"\" size=\"2\" maxlength=\"1\" id=\"letter\" />
<input type=\"submit\" name=\"submit\" value=\"Guess\" onClick=\"guessLetter()\" />

<div id=\"start_game\"><input type=\"submit\" name=\"newgame\" value=\"New Game\" onClick=\"newGame()\" /></div>"

Conclusion

Well, that wasn’t so hard now was it? Try the working version to see what it’s like! In this tutorial we took our existing PHP Hangman game and modified it to use AJAX. If you play the game you’ll see the page no longer has to refresh each time you click the guess letter button or the new game button. To accomplish this we first downloaded jQuery, created a JavaScript file to make AJAX requests, wrote a file to return a response to our AJAX requests, and then updated our hangman class to use $_GET and our new JavaScript functions.