WWWForm PHP Example

From Unify Community Wiki
Jump to: navigation, search

WWW Form php/mysql Example

This example provide a PHP alternative to the perl example on the WWWForm documentation. It assumes a table is already created for the highscores.

See the documentation for example how you would write a Unity script to communicate with the PHP script.


    // o--------------------------------------------------------
    // | Input & Settings
    // o--------------------------------------------------------

    // These variables are sent from Unity, we access them via
    // $_POST and make sure to santitize the input to mysql.
    $game     = mysql_real_escape_string($_POST['game']);
    $player   = mysql_real_escape_string($_POST['playerName']);
    $score    = mysql_real_escape_string($_POST['score']);

    // These settings define where the server is located, and
    // which credentials we use to connect to that server.  
    $server   = "localhost";
    $username = "your_username";
    $password = "your_password";
    // This is the database and table we are going to access in
    // the mysql server. In this example, we assume that we have
    // the table 'highscores' in the database 'gamedb'.
    $database = "gamedb";
    $table    = "highscores";
    // These are the MySQL queries that we are going to use when
    // we store our new score, and return our top 10 players.
    $insert   = "INSERT INTO $table (game, player, score) 
                 VALUES ('$game', '$player', '$score')";
    $select   = "SELECT * FROM $table WHERE game='$game' 
                 ORDER BY score DESC LIMIT 10";

    // o--------------------------------------------------------
    // | Access database
    // o--------------------------------------------------------

    // Connect to the server with our settings defined above.
    $connection = mysql_connect($server, $username, $password);
    // 1. Select the database to work with. 
    // 2. Insert our new player score.
    // 3. Select the top 10 players.
    $result = mysql_select_db($database, $connection);    
    $result = mysql_query($insert, $connection);
    $result = mysql_query($select, $connection);

    // Finally, go through top 10 players and return the result
    // back to Unity. The output format for each line will be: 
    // {game}:{player}:{score}
    while ($row = mysql_fetch_array($result))
        echo $row['game']   . ":" 
           . $row['player'] . ":" 
           . $row['score']  . "\n";
    // Close the connection, we're done here.
Personal tools