Getting and Posting Scores

Now we need to provide the interfaces for our program to the database. This will be by means of two php scripts; one for posting a score, the other for fetching the high score table. These will be called, with the correct parameters, from our Flash program (or indeed any program that has internet access).

 

Fetching the Highscore Table

The first script we need is getscores.php. The only parameter is gameid, which we will set to '1' for now. This is so that we can use the database to store high scores for different games.

<?php

// getscores.php

$dbh=mysql_connect ("localhost", "pc_high1", "<password>")
or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("highscores");

$sSQL = "SELECT * FROM scores where gameid = ".$_REQUEST["gameid"]." ORDER BY score DESC LIMIT 0,10";
$result = mysql_query($sSQL);

print "xml=<scores>";
while( $row = mysql_fetch_array( $result )) {
print "<name>".$row['name']."</name>";
print "<score>".$row['score']."</score>";
}
print "</scores>";
mysql_close();
?>

When you fetch this page from a web browser (you need to pass the gameid in using the querystring) it will return an XML file of the highscore table. you can test this page using a browser simply calling the URL:

http://websitesaddress/getscores.php?gameid=1

<scores>
<name>Kevin</name>
<score>12300</score>
<name>Bob</name>
<score>9200</score>
<name>Arthur</name>
<score>5005</score>
</scores>

 

That's all we need for getscores.php. Now we need a way of adding scores to the database.

 

Adding an Entry to the Highscore Table

The following script savescore.php will insert an entry into the highscores database:

<?php

// savescore.php
//
// insert score into scores database
//
$gameid = $_REQUEST["gameid"];
$name = $_REQUEST["name"];
$score = $_REQUEST["score"];
$ip = $_SERVER["REMOTE_ADDR"];
$agent = $_SERVER["HTTP_USER_AGENT"];


$dbh=mysql_connect ("localhost", "pc_high1", <password>")
or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("highscores");

$sSQL = "insert into scores(gameid, name, score, ip, agent, time)
values ($gameid, '$name', $score, '$ip', '$agent', now())";
mysql_query($sSQL) or die (mysql_error());

mysql_close();

?>

If you want to test the page, use a browser to call the URL as follows:

http://websitesaddress/savescore.php?gameid=1&name=Jack&score=15000

If you call the getscores.php page you should now have a score for "Jack". Clearly now you can see the inherent insecurity in the system. Any guy with a browser and some knowledge of how your high score system works can insert any score they like! Of course, any hacker would need to reverse-engineer your code to figure out the URL to call, and the parameters it expects. For most purposes however, this method should work just fine. I will discuss ways to make the script more secure at the end of this tutorial.

 

Next...Flash code to fetch high scores

 

( categories: )