Inserting Scores Into The Database
Inserting scores is very simple to do. We will simply make a GET request from our iPhone app to our put_score.php page and pass in information through the GET parameters. An example of this might be
http://icodeblog.com/ws/put_score.php?udid=0123456789012345678901234567890123456789&name=brandontreb&score=210.13&secret=some_secret
Here is an explanation of the variables.
Variable | Description |
---|---|
secret | This is some password that only you know. It will prevent people from inserting invalid data into your database. We will hardcode this into the script below |
udid | This is the UDID of the user’s device. It will be used to uniquely identify each user |
name | The name to display in the leadboard |
score | The score for that given user. |
And now the code for put_score.php
<?php
// put_score.php
/** MySQL database name */
define('DB_NAME', '');
/** MySQL database username */
define('DB_USER', '');
/** MySQL database password */
define('DB_PASSWORD', '');
/** MySQL hostname */
define('DB_HOST', $_ENV{DATABASE_SERVER});
$table = "highscores";
// Initialization
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
if($_GET['secret'] != "some_secret") {
die('Nothing to see here...');
}
// Localize the GET variables
$udid = isset($_GET['udid']) ? $_GET['udid'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$score = isset($_GET['score']) ? $_GET['score'] : "0.00";
// Protect against sql injections
$udid = mysql_real_escape_string($udid);
$name = mysql_real_escape_string($name);
$score = mysql_real_escape_string($score);
// Insert the score
$retval = mysql_query("INSERT INTO $table(
udid,
name,
score
) VALUES (
'$udid',
'$name',
'$score'
)",$conn);
if($retval) {
echo "Inserted score $score for $name";
} else {
echo "Unable to insert score " . mysql_error();
}
mysql_close($conn);
?>
So we see a lot of the same initialization code as we did in our create_db.php method. As you can see, there is not a lot of code here. We first just localize the GET variables and escape them to ensure that they can’t be sql injected. PHP developers are so lazy that they always fail to do this. It is one line of code that can prevent a huge security flaw.
After localization and sanitation, we simply insert these values into the database and print out the result. The last part of our server code involves displaying the leaderboard. Now, we could write a service for returning xml and display it natively in the application, however displaying a table inside of a webview is much simpler.
So, we are going to output this data into an HTML table that will get displayed inside of a UIWebView. Keep in mind that my table looks like crap and you should definitely style it before using it in your applications.