<Unity ⇔ PHP ⇔ MySQL>Unity記事: 目次
1. GitHub:https://github.com/GameFBB/MSQL
2. MySQL Table : Test
3. MSQLSample.cs ↓こんな感じで使えます
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
using MSQL; using System.Collections; using UnityEngine; /// <summary> /// /// Unity 2019.1.8f1 /// /// Unity ⇔ PHP ⇔ MySQL /// /// Table : "Test" /// /// Fields : "ObjectId", "UserName", "Score", "Age" /// /// </summary> public class MSQLSample : MonoBehaviour { ///////////////////////////////////////////////////////////////////////////////////// // Start //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// // Start is called before the first frame update private void Start() { StartCoroutine(InsertTest()); // StartCoroutine(UpdateTest()); // StartCoroutine(DeleteTest()); // StartCoroutine(FindTest()); // StartCoroutine(CountTest()); } ///////////////////////////////////////////////////////////////////////////////////// // Test ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// // Insert private IEnumerator InsertTest() { // Bobby(Score:600, Age:10) MSQLObject insert = new MSQLObject("Test"); insert.Add("UserName", "Bobby"); insert.Add("Score", 600); insert.Add("Age", 10); yield return insert.SaveAsync(); } // Update private IEnumerator UpdateTest() { // Bobby(Score:1500) MSQLObject update = new MSQLObject("Test", "UserName", "Bobby"); update.Add("Score", 1500); yield return update.SaveAsync(); } // Delete private IEnumerator DeleteTest() { // Bobby's record MSQLObject delete = new MSQLObject("Test", "UserName", "Bobby"); yield return delete.DeleteAsync(); } // Find private IEnumerator FindTest() { // TOP3 (Age >= 40) MSQLQuery query = new MSQLQuery("Test"); query.Select("UserName", "Score"); query.Where("Age", ">=", 40); // bool (true or false) query.OrderBy("Score", "DESC"); // "ASC" or "DESC" query.Limit(3); yield return query.FindAsync(); if (query.Result != null) { Debug.Log("Count : " + query.Result.Count); foreach (IDictionary data in query.Result) { Debug.Log("UserName:" + data["UserName"]); Debug.Log("Score:" + data["Score"]); } } else { Debug.Log("Not Found"); } } // Count private IEnumerator CountTest() { // Score >= 300, Age < 40 MSQLQuery query = new MSQLQuery("Test"); query.Where("Score", ">=", 300); query.Where("Age", "<", 40); yield return query.CountAsync(); Debug.Log("Count : " + query.Count); } } |
<Webサーバーに配置するPHP> ※UTF-8, BOMなし
1. mysql_connect.php ※Databaseの大文字部分を書き換え
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 |
<?php function connect() { // Database define('DatabaseHost', 'YOUR_DATABASE_HOST'); define('DatabaseName', 'YOUR_DATABASE_NAME'); define('UserName', 'YOUR_USERNAME'); define('Password', 'YOUR_PASSWORD'); // Connect try { $dsn = 'mysql:host=' . DatabaseHost . ';dbname=' . DatabaseName . ';charset=utf8'; $dbh = new PDO($dsn, UserName, Password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { exit('' . $e->GetMessage()); } return $dbh; } ?> |
2. mysql_object.php
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
<?php // Connect require_once('mysql_connect.php'); $dbh = connect(); // Parameters $method = $_POST["method"]; $table = $_POST["table"]; $targetField = $_POST["targetField"]; $targetValue = $_POST["targetValue"]; $field = json_decode($_POST["field"], true); $value = json_decode($_POST["value"], true); $result = 0; // Update, Insert, Delete try { // 1. Update if ($method == 'Update') { // Search $sql = "SELECT * FROM $table WHERE $targetField = :$targetField"; $stmt = $dbh->prepare($sql); $stmt->bindParam(":$targetField", $targetValue); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // NotExist if (count($result) == 0) { $method = 'Insert'; array_unshift($field, $targetField); array_unshift($value, $targetValue); } // Exist else if(count($result) == 1) { // UPDATE $sql = "UPDATE $table"; // SET $sql .= " SET "; for ($i = 0; $i < count($field); $i++) { if ($i > 0) { $sql .= ', '; } $sql .= "$field[$i] = :$field[$i]"; } // WHERE $sql .= " WHERE $targetField = :$targetField"; // SetParameter $stmt = $dbh->prepare($sql); for ($i = 0; $i < count($field); $i++) { $stmt->bindParam(":$field[$i]", $value[$i]); } $stmt->bindParam(":$targetField", $targetValue); // Execute $stmt->execute(); } } // 2. Insert if ($method == 'Insert') { // INSERT INTO $sql = "INSERT INTO $table ("; for ($i = 0; $i < count($field); $i++) { if ($i > 0) { $sql .= ', '; } $sql .= $field[$i]; } $sql .= ')'; // VALUES $sql .= ' VALUES ('; for ($i = 0; $i < count($field); $i++) { if ($i > 0) { $sql .= ', '; } $sql .= ":$field[$i]"; } $sql .= ')'; // SetParameter $stmt = $dbh->prepare($sql); for ($i = 0; $i < count($field); $i++) { $stmt->bindParam(":$field[$i]", $value[$i]); } // Execute $stmt->execute(); } // 3. Delete else if ($method == 'Delete') { $sql = "DELETE FROM $table WHERE $targetField = :$targetField"; $stmt = $dbh->prepare($sql); $params = array(":$targetField"=>$targetValue); $stmt->execute($params); } } catch (PDOException $e) { var_dump($e->getMessage()); } // Disconnect $stmt = null; $dbh = null; echo $sql; ?> |
3. mysql_query.php
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
<?php // Connect require_once('mysql_connect.php'); $dbh = connect(); // Parameters $method = $_POST["method"]; $table = $_POST["table"]; $select = json_decode($_POST["select"], true); $whereCount = $_POST["whereCount"]; $whereTargetField = json_decode($_POST["whereTargetField"], true); $whereOperator = json_decode($_POST["whereOperator"], true); $whereTargetValue = json_decode($_POST["whereTargetValue"], true); $orderByTargetField = $_POST["orderByTargetField"]; $orderBy = $_POST["orderBy"]; $limit = $_POST["limit"]; // Query try { // SELECT $sql = 'SELECT '; if (count($select) == 0) { $sql .= '*'; } else { for ($i = 0; $i < count($select); $i++) { if ($i > 0) { $sql .= ', '; } $sql .= $select[$i]; } } // FROM $sql .= " FROM $table"; // WHERE if ($whereCount >= 1) { $sql .= ' WHERE '; for ($i = 0; $i < $whereCount; $i++) { if ($i > 0) { $sql .= ' AND '; } $sql .= $whereTargetField[$i].$whereOperator[$i].":whereTargetValue$i"; } } // ORDER BY if ($orderByTargetField != '') { $sql .= " ORDER BY $orderByTargetField $orderBy"; } // LIMIT if ($limit != '') { $sql .= " LIMIT $limit"; } // SetParameter $stmt = $dbh->prepare($sql); if ($whereCount >= 1) { for ($i = 0; $i < $whereCount; $i++) { $stmt->bindParam(':whereTargetValue'.$i, $whereTargetValue[$i]); } } // Execute $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); //AssociativeArray } catch(Exception $e) { var_dump($e->getMessage()); } // json -> Unity if ($method == 'Find') { echo json_encode($result); } else if($method == 'Count') { echo json_encode(count($result)); } // Disconnect $stmt = null; $dbh = null; ?> |
<Unity側のスクリプト>
1. MiniJson.cs DownloadLink
2. MSQLObject.cs ※PHPのURLを書き換え
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
using MiniJSON; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; /// <summary> /// /// Unity 2019.1.8f1 /// /// MySQLのデータを操作する /// /// </summary> namespace MSQL { public class MSQLObject { ///////////////////////////////////////////////////////////////////////////////// // Field //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // PHP private readonly string url = "http://YOUR_WEB_SERVER/mysql_object.php"; // Method private string method = ""; // Table private string table = ""; // Insert private string field = ""; private string value = ""; private List<string> fieldList = new List<string>(); private List<object> valueList = new List<object>(); // Update, Delete private string targetField = ""; private string targetValue = ""; ///////////////////////////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Insert public MSQLObject(string table) { this.table = table; } // Update, Delete public MSQLObject(string table, string targetField, object targetValue) { // bool -> TINYINT(1) if (Convert.ToString(targetValue) == "True") { this.targetValue = "1"; } else if (Convert.ToString(targetValue) == "False") { this.targetValue = "0"; } else { this.targetValue = Convert.ToString(targetValue); } this.table = table; this.targetField = targetField; } // Add public MSQLObject Add(string saveField, object saveValue) { // bool -> TINYINT(1) if (Convert.ToString(saveValue) == "True") { saveValue = 1; } else if (Convert.ToString(saveValue) == "False") { saveValue = 0; } // Field fieldList.Add(saveField); // Value valueList.Add(saveValue); return this; } ///////////////////////////////////////////////////////////////////////////////// // Insert, Update /////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // SaveAsync public IEnumerator SaveAsync() { // Update or Insert if (targetField == "") { method = "Insert"; } else { method = "Update"; } // HTMLForm WWWForm form = HTMLForm(method); // Post UnityWebRequest www = UnityWebRequest.Post(url, form); yield return www.SendWebRequest(); if (string.IsNullOrEmpty(www.error)) { Debug.Log(www.downloadHandler.text); } else { Debug.Log(www.error); } } ///////////////////////////////////////////////////////////////////////////////// // Delete /////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // DeleteAsync public IEnumerator DeleteAsync() { // HTMLForm method = "Delete"; WWWForm form = HTMLForm(method); // Post UnityWebRequest www = UnityWebRequest.Post(url, form); yield return www.SendWebRequest(); if (string.IsNullOrEmpty(www.error)) { Debug.Log(www.downloadHandler.text); } else { Debug.Log(www.error); } } ///////////////////////////////////////////////////////////////////////////////// // HTML Form //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // HTMLForm private WWWForm HTMLForm(string method) { WWWForm wwwForm = new WWWForm(); // Method wwwForm.AddField("method", method); /////////// // Table // /////////// wwwForm.AddField("table", table); //////////// // Insert // //////////// // Field field = Json.Serialize(fieldList); wwwForm.AddField("field", field); // Value value = Json.Serialize(valueList); wwwForm.AddField("value", value); //////////////////// // Update, Delete // //////////////////// // TargetField wwwForm.AddField("targetField", targetField); // TargetValue wwwForm.AddField("targetValue", targetValue); return wwwForm; } } } |
3. MSQLQuery.cs ※PHPのURLを書き換え
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 |
using MiniJSON; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; /// <summary> /// /// Unity 2019.1.8f1 /// /// MySQLからデータを取得する /// /// </summary> namespace MSQL { public class MSQLQuery { ///////////////////////////////////////////////////////////////////////////////// // Field //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // PHP private readonly string url = "http://YOUR_WEB_SERVER/mysql_query.php"; // Table private string tableName = ""; // Select private string select = ""; private List<string> selectList = new List<string>(); // Where private string whereCount = ""; private string whereTargetField = ""; private string whereOperator = ""; private string whereTargetValue = ""; private List<string> whereTargetFieldList = new List<string>(); private List<string> whereOperatorList = new List<string>(); private List<object> whereTargetValueList = new List<object>(); // OrderBy private string orderByTargetField = ""; private string orderBy = ""; // Limit private string limit = ""; // Result private IList result; public IList Result { get { return result; } } // Count private int count; public int Count { get { return count; } } ///////////////////////////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Constructor public MSQLQuery(string table) { tableName = table; } ///////////////////////////////////////////////////////////////////////////////// // Query //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Select public MSQLQuery Select(params string[] fields) { for (int i = 0; i < fields.Length; ++i) { selectList.Add(fields[i]); } return this; } // Where public MSQLQuery Where(string field, string comparisonOperator, object value) { //bool -> TINYINT(1) if (Convert.ToString(value) == "True") { value = 1; } else if (Convert.ToString(value) == "False") { value = 0; } whereTargetFieldList.Add(field); whereOperatorList.Add(comparisonOperator); whereTargetValueList.Add(value); return this; } // OrderBy public MSQLQuery OrderBy(string field, string order) { orderByTargetField = field; orderBy = order; return this; } // Limit public MSQLQuery Limit(int limit) { this.limit = Convert.ToString(limit); return this; } ///////////////////////////////////////////////////////////////////////////////// // Find ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // FindAsync public IEnumerator FindAsync() { // HTMLForm WWWForm form = HTMLForm("Find"); // Post UnityWebRequest www = UnityWebRequest.Post(url, form); yield return www.SendWebRequest(); if (www == null) { Debug.Log(www.downloadHandler.text); yield break; } else { // JSON -> IList result = ConvertToIList(www.downloadHandler.text); } } ///////////////////////////////////////////////////////////////////////////////// // Count //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // CountAsync public IEnumerator CountAsync() { // HTMLForm WWWForm form = HTMLForm("Count"); // Post UnityWebRequest www = UnityWebRequest.Post(url, form); yield return www.SendWebRequest(); try { count = Convert.ToInt32(www.downloadHandler.text); } catch (Exception) { Debug.Log(www.downloadHandler.text); yield break; } } ///////////////////////////////////////////////////////////////////////////////// // HTML Form //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // HTMLForm private WWWForm HTMLForm(string method) { WWWForm wwwForm = new WWWForm(); // Method wwwForm.AddField("method", method); /////////// // Table // /////////// wwwForm.AddField("table", tableName); //////////// // Select // //////////// select = Json.Serialize(selectList); wwwForm.AddField("select", select); /////////// // Where // /////////// // Count whereCount = Convert.ToString(whereTargetFieldList.Count); wwwForm.AddField("whereCount", whereCount); // Field whereTargetField = Json.Serialize(whereTargetFieldList); wwwForm.AddField("whereTargetField", whereTargetField); // Operator whereOperator = Json.Serialize(whereOperatorList); wwwForm.AddField("whereOperator", whereOperator); // Value whereTargetValue = Json.Serialize(whereTargetValueList); wwwForm.AddField("whereTargetValue", whereTargetValue); ///////////// // OrderBy // ///////////// // Field wwwForm.AddField("orderByTargetField", orderByTargetField); // Order wwwForm.AddField("orderBy", orderBy); /////////// // Limit // /////////// if (limit == null) { wwwForm.AddField("limit", ""); } else { wwwForm.AddField("limit", limit); } return wwwForm; } ///////////////////////////////////////////////////////////////////////////////// // Json Deserialize ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // JSON -> IList private IList ConvertToIList(string jsonText) { if (jsonText == "[]") { result = null; } else { result = (IList)Json.Deserialize(jsonText); } return result; } } } |