Building Browsergames: Adding Stats (PHP)

The other day we pulled together all that we’ve built so far into the basic skeleton of what we’ll need to build our game, but we didn’t actually add anything to it to set it apart from any of the myriad other browsergames out there. Today, we’re going to start doing that – by adding stats to players.

If you’re as much of a lazy typist as I am, you’re probably wondering how you can save your fingers a bit of work and stop having to write out the 4-5 lines of code that Smarty needs in every script that uses it – and the answer is very simple. All you have to do is create a file, and save it as smarty.php – putting this inside:

1
2
3
4
5
6
7
8
9
<?php
require('/usr/share/php/smarty/Smarty.class.php');
$smarty = new Smarty();
 
$smarty->template_dir = '/web/www.domain.com/smarty/templates';
$smarty->compile_dir = '/web/www.domain.com/smarty/templates_c';
$smarty->cache_dir = '/web/www.domain.com/smarty/cache';
$smarty->config_dir = '/web/www.domain.com/smarty/configs';
?>

And then all you need to do to use it in your files is do an include() to pull the file in – and you can work off of the $smarty variable as if the code was there all along!

Now that that’s out of the way, we’re going to adjust our registration page so that it automatically sets up 3 stats for the new user – attack, defence, and magic. In order to do that, we use the function mysql_insert_id() to retrieve the last inserted auto_increment value for our connection(which we stored into $conn when we connected to the database at the start of our code).

26
			$userID = mysql_insert_id($conn);

Before we can actually make the calls from our registration page though, we’re going to need to adjust our stats code – right now, it doesn’t automatically insert a new row for the stat if the user doesn’t already have one and we try to save(only if we try to retrieve without the stat existing). We’ll add a small tweak to our stats code, by moving the code that creates rows if they don’t already exist into it’s own function that can be called anytime. This is what the code inside stats.php will look like after:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
 
function getStat($statName,$userID) {
	include 'config.php';
	$conn = mysql_connect($dbhost,$dbuser,$dbpass)
		or die ('Error connecting to mysql:');
	mysql_select_db($dbname);
	createIfNotExists($statName,$userID);
	$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
		mysql_real_escape_string($statName),
		mysql_real_escape_string($statName),
		mysql_real_escape_string($userID));
	$result = mysql_query($query);
	list($value) = mysql_fetch_row($result);
	return $value;		
}
function setStat($statName,$userID,$value) {
	include 'config.php';
	$conn = mysql_connect($dbhost,$dbuser,$dbpass)
		or die ('Error connecting to mysql');
	mysql_select_db($dbname);
	createIfNotExists($statName,$userID);
	$query = sprintf("UPDATE user_stats SET value = '%s' WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
		mysql_real_escape_string($value),
		mysql_real_escape_string($statName),
		mysql_real_escape_string($statName),
		mysql_real_escape_string($userID));
	$result = mysql_query($query);
}
 
function createIfNotExists($statName,$userID) {
	include 'config.php';
	$conn = mysql_connect($dbhost,$dbuser,$dbpass)
		or die ('Error connecting to mysql:');
	mysql_select_db($dbname);
	$query = sprintf("SELECT count(value) FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
		mysql_real_escape_string($statName),
		mysql_real_escape_string($statName),
		mysql_real_escape_string($userID));
	$result = mysql_query($query);
	list($count) = mysql_fetch_row($result);
	if($count == 0) {
		// the stat doesn't exist; insert it into the database
		$query = sprintf("INSERT INTO user_stats(stat_id,user_id,value) VALUES ((SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s'),'%s','%s')",
		mysql_real_escape_string($statName),
		mysql_real_escape_string($statName),
		mysql_real_escape_string($userID),
		'0');
		mysql_query($query);
	}	
}
 
?>

Once we’ve made that change, we can get back to our registration page – which should now have access to the new user’s User ID. We can use that in conjunction with our stats code to set their starting stats:

27
28
29
30
			require_once 'stats.php';
			setStat('atk',$userID,'5');
			setStat('def',$userID,'5');			
			setStat('mag',$userID,'5');

And you’re done! If you check out your database after registering, you’ll notice that new rows have appeared inside user_stats – one row for each stat/value pair for the user. The stats code is just what you see above, and here’s what our adjusted registration page looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
 
include 'smarty.php';
 
if($_POST) {
	$password = $_POST['password'];
	$confirm = $_POST['confirm'];
	if($password != $confirm) {
		$error = 'Passwords do not match!';	
	} else {
		require_once 'config.php';		// our database settings
		$conn = mysql_connect($dbhost,$dbuser,$dbpass)
			or die('Error connecting to mysql');
		mysql_select_db($dbname);
		$query = sprintf("SELECT COUNT(id) FROM users WHERE UPPER(username) = UPPER('%s')",
			mysql_real_escape_string($_POST['username']));
		$result = mysql_query($query);
		list($count) = mysql_fetch_row($result);
		if($count >= 1) { 
			$error = 'that username is taken.';
		} else {
			$query = sprintf("INSERT INTO users(username,password) VALUES ('%s','%s')",
				mysql_real_escape_string($_POST['username']),
				mysql_real_escape_string(md5($password)));
			mysql_query($query);			
			$userID = mysql_insert_id($conn);
			require_once 'stats.php';
			setStat('atk',$userID,'5');
			setStat('def',$userID,'5');			
			setStat('mag',$userID,'5');
			$message = 'Congratulations, you registered successfully!';
		}
	}	
}
$smarty->assign('error',$error);
$smarty->assign('message',$message);
$smarty->display('register.tpl');
 
?>

Wish there was more?

I'm considering writing an ebook - click here.

.

Luke is the primary editor of Building Browsergames, and has written a large portion of the articles that you read here. He generally has no idea what to say when asked to write about himself in the third person.

Tuesday, June 3rd, 2008 buildingbrowsergames, code, php
  • dragolux

    Make sure that you add "$userID = mysql_insert_id($conn);" to the file before you call the setStat functions.

  • Mariano

    Ive got the same problem, when register it just say it couldnt connect to mysql db, altough it adds the user in the db, it wont add the stats. Oh, and the confirmation mail wont work either.
    The problem only happen when i tried to add:
    $userID = mysql_insert_id($conn);
    require_once 'stats.php';
    setStat('atk',$userID,'5');
    setStat('def',$userID,'5');
    setStat('mag',$userID,'5');

    anyone can help me out? thanks in advance

  • Casey

    Is there any info on making the user_stats table?

  • Yes - it was created at
    http://buildingbrowsergames.co...
    .

  • I can't get it to work.

    It just won't add the stats.

  • You're going to have to give me more information in order for me to help
    you; do they not insert into the database? Does it not update them? What
    "doesn't work"?
    My first suggestion would be redoing the tutorial, and making sure that you
    follow each step exactly - typically these sorts of problems crop up because
    you've missed a step, or skipped ahead.

  • MrLollige

    Why did you switch over to Include instead of Require_once?

blog comments powered by Disqus

About

Building Browsergames is a blog about browsergames(also known as PBBG's). It's geared towards the beginner to intermediate developer who has an interest in building their own browsergame.

Sponsors

Got Something to Say?

Send an e-mail to luke@buildingbrowsergames.com, or get in touch through Twitter at http://twitter.com/bbrowsergames