TUTORIAL: How to make your app talk to a web service.... or how to setup a web service for your app to talk to....

This topic comes up frequently and the thought of writing a tutorial on how to set up a MySQL database, create a table, populate it with data just to get to a point to where you could write a tutorial on writing a simple PHP script to read the data and have it talk with your app is well… daunting… frightening… and more work than anyone really has time for.

So I present to you an attempt to write this tutorial for you…

http://wp.me/p1K9f6-6O

NOTE: I wrote this quickly. I didn’t even bother to proof read it. I’m tried and cranky. If any one wants to be my editor, let me know and I’ll give you access…

I took this from working code for an app I’m building, but in sanitizing it for public consumption, I may have broken something. Did I mention I’m tired.

It’s by no mean thorough, but it’s a start.

Comments, Criticism, Candy, Cans of Beer and Cash always welcome.

[import]uid: 19626 topic_id: 24922 reply_id: 324922[/import]

Hey Rob,

I look forward to checking this out, I’m sure it’s great :slight_smile:

Hope you can get some sleep! [import]uid: 52491 topic_id: 24922 reply_id: 101191[/import]

Thank you for sharing, Rob!

The thought of setting up a MySQL database and everything else that comes along with it feels like a truly frightening process – but then, everything techie feels frightening to me until I learn how to do them. So, when some unexpected circumstances force me to tackle this uncharted area, hopefully your tutorial will help dispel my avoid-it-at-all-cost attitude toward databases, servers, etc.

Cheers,
Naomi
[import]uid: 67217 topic_id: 24922 reply_id: 101200[/import]

Thanks, Rob.

Any advice as to whether a developer new to the backend development process should just focus on using a BaaS option like Parse now that Corona’s network API has been updated to handle POST and DELETE (and can connect to Parse via the REST API)? [import]uid: 135391 topic_id: 24922 reply_id: 101202[/import]

@naomi and @nate, Database Administration (DBA) is an entire career field. There is a lot to know about them and its not a job for the feint of heart when it comes to techology.

Luckily, with the right tools and a few tutorials, you should be able to setup a simple database and read and write data from it without too terrible. On top of that writing apps to access the database and fetch and retrieve the data is a whole other layer of skills and expertise that not only requires understanding how to query databases, but understanding how web servers work and how to properly transmit data.

My advice to any one who doesn’t have those skills and perhaps who doesn’t want them is to use a service like Parse or contract out the work to someone who has the skills to make it happen.

Now if you’re a learner and want to dive into an exciting area of app development that has the potential to land you big jobs, knowing that side of the fence looks really good on your resume.
[import]uid: 19626 topic_id: 24922 reply_id: 101295[/import]

rob,
I am new to php and mysql but i was able to follow your tutorial pretty easily. Very well written and thank you for it. That being said i am having a problem with connecting to mysql. I setup the database just like yours, my database is called scores with a players array in it and in that array are the columns for id, player name, first name, last name, password, and last login, i filled those rows out and make a few user names but when i try to access the info in the simulator all i get is a blank “RESPONSE:” with no errors or responses, and when i push it to android i get a network error. Ive also tried filling out the url and taking out the encoding so its just a strait up username and pass and putting that in a web browser with no response at all, just a blank page. Any idea what this could be? after some troubleshooting it looks like it could be a multitude of things but any ideas that could help me narrow it down? thanks in advance and thanks again for the tut. [import]uid: 126161 topic_id: 24922 reply_id: 105154[/import]

It sounds like there may be a problem in the PHP script.

I would first, figure out exactly what URL your app is trying to send, then put that URL directly into a browser and see what is being dumped to the browser window. PHP errors will likely show up there, that wouldn’t necessarily show up in the response in your app.

You can also add debugging statements to your PHP file using “echo” (which is like Lua’s “print”) and look for errors and such in not getting connectivity to your database.

And as always, its going to be hard to help you without seeing code.

[import]uid: 19626 topic_id: 24922 reply_id: 105167[/import]

Rob,
The code i am using is just copied and pasted from your site. I finally got it to connect after some changes. I had to add an email column to my array and had to call
[php]
mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
echo "Connected to MySQL
";
[/php]
before the if statement for it to connect and not give me the errors, also i had to take out the md5 in the string compare because my password is just a string and not encrypted.
[php]

<?php
define("DB\_DSN",'database'); define("DB\_HOST",'localhost'); define("DB\_USER",'admins'); define("DB\_PASS",'pass'); mysql\_connect(DB\_HOST, DB\_USER, DB\_PASS) or die(mysql\_error()); echo "Connected to MySQL "; mysql\_select\_db(DB\_DSN) or die(mysql\_error()); echo "Connected to Database"; $link = mysql\_connect(DB\_HOST, DB\_USER, DB\_PASS) or die('Could not connect: ' . mysql\_error()); if(isset($\_GET)) { $playername = base64\_decode($\_GET["playername"]); $password = base64\_decode($\_GET["password"]); $query = 'SELECT \* FROM players WHERE playername="' . mysql\_real\_escape\_string($playername) . '" or email="' . mysql\_real\_escape\_string($loginid) . '"'; $dbresult = mysql\_query($query, $link); if (!$dbresult) { //echo "query failed"; $result = array(); $result["result"] = 403; $result["message"] = mysql\_error(); echo json\_encode($result); mysql\_free\_result($dbresult); exit; } $player = mysql\_fetch\_array($dbresult, MYSQL\_ASSOC); if (strcmp($player["password"],$password) == 0) { $result = array(); $result["result"] = 200; $result["message"] = "Success"; $result["playername"] = $player["playername"]; $result["firstname"] = $player["firstname"]; $result["lastname"] = $player["lastname"]; $query = sprintf("UPDATE players SET lastlogin=NOW() WHERE id=%s;", $player["id"]); $uresult = mysql\_query($query, $link); if ($uresult) { //code if your update failed. Doesn't really impact what we are doing. so do nothing. } echo json\_encode($result); } else { //echo "password mismatch"; $result = array(); $result["result"] = 403; $result["message"] = "Forbidden"; echo json\_encode($result); } } else { $result = array(); $result["result"] = 400; $result["message"] = "Bad Request"; echo json\_encode($result); } exit; [/php] and here is the lua code im using [lua]local mime = require("mime") local json = require("json") local playerName = "userid" local password = "password" local responseText = display.newText ("Nothing Yet", 0, 0, native.systemFont, 24) responseText.x = 160; responseText.y = 75; local URL = "http://server.com/scores.php?playername=" .. mime.b64(playerName) .. "&password=" .. mime.b64(password) local function loginCallback(event) if ( event.isError ) then print( "Network error!") responseText.text = "Network Error!" else print ( "RESPONSE: " .. event.response ) local data = json.decode(event.response) responseText.text = "RESPONSE: "..event.response print (data.result) -- do with data what you want... end return true end local function callreq () network.request( URL, "GET", loginCallback ) end local button = display.newCircle (0, 0, 40) button.x = 160; button.y = 240 button: addEventListener ("tap", callreq)[/lua] the only problem i am having now is that when i try to get the data from the local data it is still nill and the response i get from the server is RESPONSE: Connected to MySQL Connected to Database{"result":200,"message":"Success","playername":"ryanr","firstname":"ryan","lastname":"robinson"} but still no data, any suggestions oh guru of the databases [import]uid: 126161 topic\_id: 24922 reply\_id: 105173[/import]

mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());echo "Connected to MySQL";mysql_select_db(DB_DSN) or die(mysql_error());echo "Connected to Database";[/code]You need to take out any debug statements like those echo's when your app makes the call. That extra text is making the expected JSON data invalid. [import]uid: 19626 topic_id: 24922 reply_id: 105178[/import]

That was it, thats why you are the database guru. Again this is my first day working with php and mysql and with your tutorial i was able to get it fully working so thanks again! Now i can go on my own and learn to write data to the database and create/manage logins within the app. Thanks again. [import]uid: 126161 topic_id: 24922 reply_id: 105179[/import]

You’re quite welcome. I’m happy you have it working. I however am not a database guru. I know enough to survive.

Rob [import]uid: 19626 topic_id: 24922 reply_id: 105181[/import]

Thanks a lot, great tutorial. I have everything up and running, and it worls like a charm.
Unfortunately i have hit the 8kb data limit, my table is up to 100kb.

Anybody knows what to do ?

Thanks
Tommy
[import]uid: 128204 topic_id: 24922 reply_id: 111178[/import]

I have a question. What do I need before this tutorial? a muSQL account or program or something? I am not sure. Also, do i need a server?

And in the tutorial, the code “on server side”, where do I insert it?

Soor I have never done anything like this
[import]uid: 130035 topic_id: 24922 reply_id: 112907[/import]

I’m not sure what 8K data limit your referring to @thassman… Most hosting companies have practically unlimited sizes for databases. With out seeing your database schema and how you’re trying to manage your records, its going to be hard to give any advice.

@deleurapps… There are various setups that one can use, but the typical setup is you need:

  1. A hosting account. Check out hostgator.com. This is where you could host a dedicated website, run a blog or whatever you want. You need a web server that will respond to your apps requests. If you follow my tutorial, this website would need to support PHP or some other language that can talk to the database and input/output responses from the web.

  2. A database server. Most hosting accounts give you the ability to create MySQL databases. Account wise, once you create the database, you will have a username/password that you use to manage the database and typically you would create a separate username/password database user for your API.

If you don’t want to go through the work of hosting your own website, you can check with services like Parse which offer to do your database hosting for you. Several people have built wrappers around the Parse API for Corona/Lua
[import]uid: 19626 topic_id: 24922 reply_id: 112910[/import]

@robmiracle, GREAT CODE, we are adding downloading of our IN-App Items this way

@3 Dreams Gaming, - thanks for the code tweaks - works great :slight_smile:

Larry

[import]uid: 11860 topic_id: 24922 reply_id: 112923[/import]

Umm Great tutorial I followed it and everything worked. Except that Last Login Doesnt get updated

Update: Never mind I forgot to change a part of the code
[import]uid: 130035 topic_id: 24922 reply_id: 113123[/import]

Does anyone know a php code in which:

  1. You recieve a score and the device id from the application
    2.If the device id is already entered in the mysql table then the score gets updated
  2. If the device ID is not entered yet then it makes a new entry which states the device ID and the score

I am sorry I have never used PHP

I tried writing it and here is what I got:

It doesnt work but its a begining

[php]

<?php
define("DB\_DSN",'database'); define("DB\_HOST",'localhost'); define("DB\_USER",'user'); define("DB\_PASS",'pass'); mysql\_connect(DB\_HOST, DB\_USER, DB\_PASS) or die(mysql\_error()); mysql\_select\_db(DB\_DSN) or die(mysql\_error()); $link = mysql\_connect(DB\_HOST, DB\_USER, DB\_PASS) or die('Could not connect: ' . mysql\_error()); if(isset($\_GET)) { $DeviceID = base64\_decode($\_GET["DeviceID"]); $DHS = base64\_decode($\_GET["DHS"]); $EHS = base64\_decode($\_GET["EHS"]); echo $DeviceID, $DHS, $EHS; $sql\_result = mysql\_query("SELECT DeviceID FROM Test2 WHERE DeviceID = ". $DeviceID ) or die(mysql\_error()); if(mysql\_num\_rows($sql\_result) \> 0 ){ mysql\_query("UPDATE `Test2` SET `DHS`= " . $DHS . ",`EHS`= " . $EHS . " WHERE DeviceID = ". $DeviceID ); } else{ mysql\_query("INSERT INTO `Test2`(`DeviceID`, `DHS`, `EHS`) VALUES (" . $DeviceID. "," . $DHS. "," . $EHS ); } } ?\> [/php] and on the app side: [code] local mime = require("mime") local json = require("json") local DeviceID = "1223412" local DHS = "10032" local EHS = "69340673" local URL = "http://server.com/test2.php?DeviceID=" .. mime.b64(DeviceID) .. "&DHS=" .. mime.b64(DHS).. "&EHS=" .. mime.b64(EHS) local function loginCallback(event) if ( event.isError ) then print( "Network error!") responseText.text = "Network Error!" else print ( "RESPONSE: " .. event.response ) local data = json.decode(event.response) -- do with data what you want... end return true end network.request( URL, "GET", loginCallback ) [/code] [import]uid: 130035 topic\_id: 24922 reply\_id: 113129[/import]

Its a great start but why all the periods in your select, update, and insert strings? Here is a working example strait from our leaderboards that does exactly what you are asking for:

[php]
$checkUser = “SELECT * FROM $puz WHERE user = ‘$username’”;
$query = mysql_query("$checkUser");
$countOcc = mysql_num_rows($query);

if ($countOcc > 0 ){
$checkScore = “SELECT msscore FROM $puz WHERE user = ‘$username’”;
$checkQuery = mysql_query("$checkScore");
$checkScoreAmt = mysql_fetch_assoc($checkQuery);

if ($checkScoreAmt[“msscore”] > $ms ) {
$changeQuery = “UPDATE $puz SET msscore = ‘$ms’ WHERE user = ‘$username’”;
mysql_query($changeQuery);
$results = array();
$results[“result”] = 200;
echo json_encode($results);
mysql_close();
} else {
$results = array();
$results[“result”] = 100;
echo json_encode($results);
mysql_close();
}
} else {
mysql_query(“INSERT INTO $puz (user, id, msscore)
VALUES( ‘$username’, ‘$userid’, ‘$ms’)”);
$results = array();
$results[“result”] = 200;
echo json_encode($results);
mysql_close();
}
[/php]

See if you can pull what you need out of that, but keep in mind, our leaderboards go by the fastest time so its the lowest score thats the best.

This code will check for a matching username, if it matches it will see if there is a score that is lower than the score that is trying to be posted, if there is then it will not post a new score, but if the score is higher than the score trying to be posted then it will update the current score. Also if no score from that user can be found then it will add a new score to the table. [import]uid: 126161 topic_id: 24922 reply_id: 113156[/import]