LoginSignup
24
27

More than 5 years have passed since last update.

Unity/PHP/MySQLを使って遊んでみる

Last updated at Posted at 2015-08-15

Unityからデータベースのusersテーブルの更新と参照を行います。


Unity

LitJsonを使ってJSONデータで通信します。
サーバーから受信したusersテーブルのレコードをDBUsersクラスのインスタンスで保持します。

usersテーブルのレコードを表すクラス
public class DBUsers {
    public int id { get; set; }
    public string name { get; set; }
    public int score { get; set; }
}

id = 1 のレコードに name = "superman" と score = 100 を設定します。

PHPを経由してデータベースの更新と参照を行う
using UnityEngine;
using System.Collections;
using LitJson;

public class TestPHP : MonoBehaviour {

    public string url = "http://sample.local/index.php";

    void Start() {
        StartCoroutine (SetUserTest ());
    }

    IEnumerator SetUserTest() {
        DBUsers sendData = new DBUsers ();
        sendData.id = 1;
        sendData.name = "superman";
        sendData.score = 100;
        WWWForm form = new WWWForm ();
        form.AddField ("user", JsonMapper.ToJson(sendData));
        using (WWW www = new WWW(url, form)) {
            yield return www;
            if (! string.IsNullOrEmpty (www.error)) {
                Debug.Log ("error:" + www.error);
                yield break;
            }
            Debug.Log ("text:" + www.text);
            DBUsers user = JsonMapper.ToObject<DBUsers>(www.text);
            Debug.Log("id:"+user.id+", name:"+user.name+", score:"+user.score);
        }
    }
}

PHP

受け取ったPOSTデータでデータベースを更新します。
データベースにはPDOを使ってアクセスします。
PDO::FETCH_CLASSを指定するとデータベースの内容をクラスを使って受け取れます。

index.php
<?php

define('DB_DATABASE', 'test_db');
define('DB_USERNAME', 'dbuser');
define('DB_PASSWORD', 'dbpasswd');
define('PDO_DSN', 'mysql:dbhost=localhost;dbname='.DB_DATABASE);

/////////////////////////////////////
// POST.
function CheckPostNumeric($key) {
    if (is_numeric($_POST[$key])) {
        return (int)$_POST[$key];
    }
    return 0;
}

function CheckPostString($key) {
    if (is_string($_POST[$key])) {
        return $_POST[$key];
    }
    return "";
}

function CheckPostJson($key) {
    if (is_string($key)) {
        return json_decode($_POST[$key]);
    }
    return null;
}

/////////////////////////////////////
// JSON.
function CheckJsonNumeric($val) {
    if (is_numeric($val)) {
        return (int)$val;
    }
    return 0;
}

function CheckJsonString($str) {
    if (is_string($str)) {
        return $str;
    }
    return "";
}

/////////////////////////////////////
class User {
    public function ToJson() {
        $this->id = CheckJsonNumeric($this->id);
        $this->name = CheckJsonString($this->name);
        $this->score = CheckJsonNumeric($this->score);
        return json_encode($this);
    }
}

$postUser = CheckPostJson('user');

header('Content-type:application/json');

try {
    $db = new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare("update users set name = :name, score = :score where id = :id");
    $stmt->bindValue(':id', $postUser->id, PDO::PARAM_INT);
    $stmt->bindValue(':name', $postUser->name, PDO::PARAM_STR);
    $stmt->bindValue(':score', $postUser->score, PDO::PARAM_INT);
    $stmt->execute();

    $stmt = $db->prepare("select * from users where id = :id");
    $stmt->bindValue(':id', $postUser->id, PDO::PARAM_INT);
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_CLASS, 'User');
    foreach ($users as $user) {
        echo $user->ToJson();
    }

    $db = null;
} catch (PDOException $e) {
//  $db->rollback();
    echo $e->getMessage();
    exit;
}

MySQL

MySQLの環境を用意するには、ドットインストールさんが分かりやすくてよかったです。
ローカル開発環境の構築 [MacOS X編]
PHPデータベース入門

MySQLコマンド
mysql> create database test_db;
mysql> grant all on test_db.* to dbuser@localhost identified by 'dbpasswd';
mysql> use test_db;
mysql> create table users ( id int not null auto_increment primary key, name varchar(255), score int );
mysql> insert into users ( name, score ) values ( 'testman', 30 );

Unityを実行して、データベースが更新されれば成功です。

24
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
27