Jump to content


Photo

MySQL Demo for GM-HTML 5


  • Please log in to reply
52 replies to this topic

#1 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 25 September 2011 - 02:55 AM

GM-HTML 5 SQL Demo

With the advent of GM-HTML5, communicating with a MySQL database may prove an extremely useful resource for storing information. This is a simple guide to help you get started. For this example, we will be looking at a virtual basket of apples. Our database can hold a total of 16 apples - 8 green and 8 red.

If you're impatient or really don't care about how the process is done, check out the live example here.

Part 1 - Code

Step 0 - Basic Understanding of the Process

Like a lot of web development, this process will span multiple languages.

We will use GameMaker to execute a script from a JavaScript file. The JavaScript command loads a PHP file without reloading the page (AJAX). That PHP file has the ability to manipulate the MySQL database. After doing that, the PHP file can return data by displaying information needed to be returned. The JavaScript will accept that data and report it back to GameMaker.

This is not a guide for learning PHP, GML, JavaScript or SQL. It assumes that you have at least a basic understanding of all four languages. Without moderate PHP and SQL knowledge, manipulating the database may prove difficult. Refer to the PHP-MySQL guide at w3schools to learn more.

Step 1 - JavaScript

We will use JavaScript (AJAX) to execute a PHP file that contains the functions we wish to use. It returns the text that would be displayed on the PHP page if it was loaded by itself.

Parameters:
url - (String) Path to the PHP file with appended arguments.
async - (0 or 1) Run the command asynchronously (1) or synchronously (0).

function SQLCommand(url,async) {
   if (window.XMLHttpRequest) {
      xmlObject = new XMLHttpRequest();
   } else {
      xmlObject = new ActiveXObject("Microsoft.XMLHTTP");
   }
   
   xmlObject.open("GET",url,async);
   xmlObject.send(null);

   return xmlObject.responseText;
}

For the most part, you won't have to edit this function.

Step 2 - PHP

PHP will be used to actually speak with the MySQL database and carry out the desired actions. If a value is to be returned, the PHP function will simply echo the result onto the page, which the JavaScript function above will read and report back to GameMaker.

We'll start with two standard functions that we'll use to connect and close the connection to the database. I've removed the login information in my example for obvious reasons.

<?
   // database variables
   $dbHost = "localhost";
   $dbName = "<name here>";
   $dbUser = "<user here>";
   $dbPass = "<password here>";

   // database connection functions
   function dbConnect() {
      global $dbCon, $dbHost, $dbName, $dbUser, $dbPass;
      $dbCon = mysql_connect($dbHost,$dbUser,$dbPass);
      return mysql_select_db($dbName);
   }
   
   function dbClose() {
      global $dbCon, $dbHost, $dbName, $dbUser, $dbPass;
      mysql_close($dbCon);
      unset($dbCon);
   }
?>

Now need a table in the database, which is our virtual apple basket.

Our basket of apples will be a table consisting of three fields:
1) appleid (INT) - a unique identifier for the apple
2) color (TINYTEXT) - the apple color (green or red)
3) weight (INT) - the weight, in grams, of the apple

We can use PHP or phpMyAdmin to create the table. The following PHP code will suffice.

<?
   // connect to the database
   dbConnect();

   // create the table
   mysql_query("CREATE TABLE apples
      (
         appleid int NOT NULL AUTO_INCREMENT,
         PRIMARY KEY(appleid),
         color TINYTEXT,
         weight INT
      )
   ");

   // close the connection to the database
   dbClose();
?>

Now that we have a table to operate on and an easy way to connect to the database, we can define our custom functions. The PHP file accepts a standard argument, act, which decides which function to execute. Therefore, we have a switch statement that designates program control. Our example has three functions: Get apple lists, add an apple to a list and empty the entire basket.

<?
   // custom SQL functions
   switch($_GET['act']) {
      case "getApples":
         dbConnect();
         $qry = mysql_query("SELECT * FROM apples WHERE color='$_GET[color]'");
         $compile = "";
         while ($data = mysql_fetch_array($qry)) {
            if ($compile != "") $compile .= "|";
            $compile .= $data['weight'];
         }
         dbClose();
         echo $compile;
         
         break;
      
      case "addApple":
         dbConnect();
         mysql_query("INSERT INTO apples VALUES ('','$_GET[color]','$_GET[weight]')");
         dbClose();
         
         break;
      
      case "removeApples":
         dbConnect();
         mysql_query("TRUNCATE TABLE apples");
         dbClose();
         
         break;
   }
?>

With the argument of "getApples", the PHP file will use the additional argument of "color" to return a list in the form "x|y|z|..." of the weights of all apples of that color. The "addApple" command will insert a new apple into the basket with the specified color. The "removeApples" command will simply truncate the table, emptying the basket completely. Notice how in order to return a value, we simply echo the information to display it on the page. Users never actually see this information - it is read by the JavaScript AJAX and returned to GameMaker.

Step 3 - GameMaker

Now that we have PHP to talk to the database and JavaScript to talk to the PHP, we need the GameMaker generated HTML5 to talk to the JavaScript. In a new GM-HTML5 project, we create a new extension that employs the use of the function we wrote in the beginning of the demonstration. Refer to this tutorial by JacksonYarr if you have difficulty with this step. Assign the name of the function SQLCommand with two arguments (string, double), and a string return type.

After we've imported the AJAX JavaScript function, we're essentially all set. Use the SQLCommand(url,async) function to load the PHP file with your desired parameters.

For our apple basket example, the logical first course of action is to create a script that updates the lists of green and red apples.

// updateApples();
// retrieve the green and red apples from the database
global.applesGreen = string_parse(SQLCommand("sql.php?act=getApples&color=green",0),"|",true);
global.applesRed = string_parse(SQLCommand("sql.php?act=getApples&color=red",0),"|",true);

I'm using the string_parse script from GMLScripts.com, which I will provide the source to at the bottom of this post. The string_parse function takes the returned list of "x|y|z|..." and converts it into a ds_list containing the elements {x, y, z, ... }, much like the explode function of PHP.

Let's take a closer look at how GameMaker is getting the lists from the database. In particular, the list of green apples.

We call SQLCommand("sql.php?act=getApples&color=green",0) to get the raw list of green apples. You can see from the URL, the argument act is set to the function getApples, and the argument color is set to green. Refer back to our PHP function to see how these arguments direct program flow. We have the async parameter set to 0 in order to have the program wait for the SQL statement to go through before our program continues.

To add an apple to the basket, we simply use the addApples function. Remember, we don't want the basket to have more than 8 apples of each kind.

// add a green apple with a random weight into the database
if (ds_list_size(global.applesGreen) > 7) {
   show_message("You can only have eight green apples at a time!");
} else {
   randomWeight = random_range(100,250);
   SQLCommand("sql.php?act=addApple&color=green&weight="+randomWeight,0);
}

// update the apple counts
updateApples();

This code adds a green apple to the database, for reasons that I hope are now perfectly clear. Afterwards, we update the lists again to account for the new apple.

The procedure to empty the basket follows the same steps as the other SQL commands.

Part 2 - Example

View a live version of this example here. Note that multiple people may be accessing the example, so if you add one apple and two appear, it is because a different user added another.

It appears that exporting an editable project is not completely functional. When that is fixed, I will upload the editable example.
  • 12
Posted ImagePosted Image

#2 Mayhem Games

Mayhem Games

    Proud Kiwi

  • GMC Member
  • 959 posts
  • Version:GM:Studio

Posted 25 September 2011 - 02:59 AM

I was trying to do this yesterday but my fail PHP skills let me down :tongue: Thank you this will be very useful, this shows how powerful Game Maker HTML5 can be.
  • 0

For a long time it puzzled me how something so expensive, so leading edge, could be so useless, and then it occurred to me that a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a dangerously perfect match. ~ Bill Bryson


#3 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 25 September 2011 - 03:06 AM

You don't need extensive PHP skills to manipulate a MySQL database. Check out the PHP-MySql tutorial at W3Schools to learn everything you'll need to know. (Added this into the main post).
  • 0
Posted ImagePosted Image

#4 xot

xot

    GMC Dismember

  • GMC Elder
  • 4785 posts
  • Version:GM:Studio

Posted 25 September 2011 - 03:08 AM

Very nice!
  • 0
GMLscripts.com, rise from your grave!

If any of my posts contain broken images or links, I can probably supply them for you. PM with a link to the post.

#5 OMGCarlos

OMGCarlos

    GMC Member

  • GMC Member
  • 329 posts
  • Version:GM:HTML5

Posted 25 September 2011 - 03:13 AM

Awesome work and tutorial...I keep saying this but GM HTML5 FTW!
  • 0

#6 BlaXun

BlaXun

    Slime Online Creator

  • GMC Member
  • 2750 posts
  • Version:GM:Studio

Posted 25 September 2011 - 09:16 AM

Yeah, this seems to be great...but it feels a lil slow in your example.

Edit:
I tried this right now...it doesn't work for me.

This is a weird behavior I get here:
http://it-liebig.com...mple/index.html

I use everthing as you wrote, and in the first room there is simply a "controller" object which does the following in its create event:

show_message("runnning")

global.res = string_parse(SQLCommand("connect.php?act=Read",0),"|",true)

for (i=0; i<= ds_list_size(global.res);i+=1)
{
 show_message(ds_list_find_value(global.res,i))
}

show_message(string(ds_list_size(global.res)))

You will notice that the "running" is shown all the time... nothing else.
Well, missbehavior of GM ...or stupid developer (this means me...not u ;) )

Edit:
Nevermind, finally got it to work.
Thanks again

Edited by BlaXun, 25 September 2011 - 10:54 AM.

  • 0

iBNKRoX.png


#7 Manuel777

Manuel777

    InvaderGames

  • GMC Member
  • 3578 posts
  • Version:GM:Studio

Posted 25 September 2011 - 10:49 AM

Absolutely great! :)
  • 0

@MEtchegaray7

gplussignature.png

May this signature be frozen on the old GMC until the end of times. Or YoYo takes it down.


#8 Mark Overmars

Mark Overmars

    Game Maker Creator

  • GMC Elder
  • 805 posts
  • Version:Unknown

Posted 25 September 2011 - 12:23 PM

Should be easy to use this to maintain an online highscore list for your game, wouldn't it? It would be useful if somebody did build this in such a way people can easily include it in their game.


If somebody has a webserver with enough room, you could even provide a single database for everybody to use to store the highscores for their games, that is, store all the different highscore lists in a single database. The game would just need to provide some unique key to access the data for his own game. Might not be so safe though.
  • 2
Mark Overmars, YoYo Games, www.yoyogames.com

Twitter:
twitter.com/mark_overmars
Check out my book The Game Maker's Apprentice
Buy my iPhone/iPad/Android game Super Snake HD

#9 BlaXun

BlaXun

    Slime Online Creator

  • GMC Member
  • 2750 posts
  • Version:GM:Studio

Posted 25 September 2011 - 12:28 PM

Yes, extremely helpful for online highscore.

However... I think this is far too much for a online highscore.

Simply writing to a text-file on the server would allready be enough for that :P

Anyway:
A HTML5 SQl-supported Chat made in Game Maker

http://it-liebig.com...Chat/index.html

Sorry, very uncomfortable right now... sometimes keys arent recognized... not keys supported besides characters (some functions in GM4HTML5 are currently broken, ex: keyboard_string, keyboard_lastchar)

Edit:
I am not rly sure if the ASYNC works, my chat sample should call the function async, but it still hangs and sometimes wont accept key input in the chat due to this.

Edited by BlaXun, 25 September 2011 - 01:00 PM.

  • 0

iBNKRoX.png


#10 Mark Overmars

Mark Overmars

    Game Maker Creator

  • GMC Elder
  • 805 posts
  • Version:Unknown

Posted 25 September 2011 - 03:28 PM

How would you write to a textfile on the server? You would need something for that on the server side. And nothing is more logical than storing scores in a database I think.
  • 0
Mark Overmars, YoYo Games, www.yoyogames.com

Twitter:
twitter.com/mark_overmars
Check out my book The Game Maker's Apprentice
Buy my iPhone/iPad/Android game Super Snake HD

#11 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 25 September 2011 - 04:58 PM

I am not rly sure if the ASYNC works, my chat sample should call the function async, but it still hangs and sometimes wont accept key input in the chat due to this.

If async is set to 0, the program will wait for the command to be finished before continuing program flow. If async is set to 1, the program will not wait for the command to be finished before continuing program flow.

And nothing is more logical than storing scores in a database I think.

Absolutely!

MySQL can even sort the highscore lists and return the top (x) for you.

SELECT * FROM highscores ORDER BY score DESC LIMIT 0,10

The above code will return the top 10 scores in sorted order.

When I get some time, I'm plan on rewriting this entire tutorial. I'll also add a highscore tutorial since it would be much more useful. I'll also put emphesis on how this is a guide that shows the general procedure for talking to a server - modifying the PHP file can change the program from using SQL to textfiles, or anything else PHP can do.

Thanks for the responses!
  • 0
Posted ImagePosted Image

#12 BlaXun

BlaXun

    Slime Online Creator

  • GMC Member
  • 2750 posts
  • Version:GM:Studio

Posted 25 September 2011 - 05:02 PM

Yeah, I tried teh async option in both ways, but as you can see (My SQL powered Chat) it still doesnt recognize Keyboard_press sometimes...and I cant figure out the reason...there is not much code anyway...makes me wonder if the async call doesnt block somehow.
  • 0

iBNKRoX.png


#13 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 25 September 2011 - 05:04 PM

Try it without the whole SQL system; make sure it's not simply lag from HTML5.
  • 0
Posted ImagePosted Image

#14 paul23

paul23

    GMC Member

  • Global Moderators
  • 4147 posts
  • Version:GM:Studio

Posted 25 September 2011 - 05:09 PM

$qry = mysql_query("SELECT * FROM apples WHERE color='$_GET[color]'");


What would happen if I fed it color as:

green';DROPTABLE apples;SELECT * FROM apples WHERE color='green



You might wish to add some extra about code injection :P
  • 0

#15 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 25 September 2011 - 05:17 PM

$qry = mysql_query("SELECT * FROM apples WHERE color='$_GET[color]'");


What would happen if I fed it color as:

green';DROPTABLE apples;SELECT * FROM apples WHERE color='green



You might wish to add some extra about code injection :P

Good point, I'll add in a security section outlining the importance of mysql_escape_string().
  • 0
Posted ImagePosted Image

#16 Razon

Razon

    GMC Member

  • GMC Member
  • 268 posts
  • Version:GM:Studio

Posted 25 September 2011 - 06:49 PM

Instead of mysql_escape_string, I recommend the use of mysql_real_escape_string. Because it makes sure to match the proper character set used with the SQL database, and makes sure that all of the characters are escaped correctly. The prior function is also deprecated and will throw a notice in newer PHP versions, on a side note you'll need a database connection established before you can use it.

You should also take into consideration whether magic quotes are enabled for php on the server or not, if so then you need to use stripslashes before escaping it with the mysql function so that there isn't any extra filtering left over on the text.

Edited by Razon, 25 September 2011 - 09:47 PM.

  • 1

#17 BlaXun

BlaXun

    Slime Online Creator

  • GMC Member
  • 2750 posts
  • Version:GM:Studio

Posted 25 September 2011 - 06:59 PM

Yes please.
I'd like some security infos too ^^,

And another thing...any idea how to prevent users from simply calling the php script directly and adding the variables with ridiculus highscores?
  • 0

iBNKRoX.png


#18 Alert Games

Alert Games

    GMC Member

  • GMC Member
  • 1119 posts
  • Version:GM8

Posted 25 September 2011 - 11:39 PM

@Blaxun: I have experience doing this as my website currently does this.

The only way to keep it as secure as possible would be to fetch the time from the server, set a degree of variability in the PHP file, and encrypt the time with the data send to check if it is a legit action.

Unfortunately, as you are calling javascript functions for both fetching the time, and for sending the information. Therefore, this only prevents easy hacking.

But on top of that, you need to encrypt the contents with an algorithm that does not use characters that may be escaped in a URL. This may be able to be avoided with careful work in the PHP, but I chose to create my own alogorithm. (plus, you MUST use a GML version of the algorithm for HTML5)

Heres a quick rundown:
1. Fetch the server time using a 'SQLcommand' in this case.
2. Combine the secure information sent into a string, including the time, and hash it using an alogorithm that does not interfere with the URL escaping.
3. 'Compile' the information to be sent. This includes the new hash of all the contents.
4. Have the PHP compare the hash, by hashing the contents the way you hashed it in GM.
5. Compare the time with the server time, checking if it is within the degree of variability.
6. Do the database stuff.
7. Send back the results.

On a side note, I wonder if you could use a memory hack or script hack on the game? If so, you would need to also hash important information like the score, lives, etc. or else people can cheat easily that way as well.

Edited by Alert Games, 25 September 2011 - 11:41 PM.

  • 0

#19 aiacono

aiacono

    GMC Member

  • New Member
  • 13 posts

Posted 26 September 2011 - 01:53 AM

You should use an extension like Fake Callback if you want async requests. Otherwise xhr.responseText isn't going to be available to your Game Maker objects.
  • 0

#20 tomasart

tomasart

    GMC Member

  • GMC Member
  • 269 posts

Posted 26 September 2011 - 02:08 PM

This is not for store Highscores. This is for logical storage.

- store user accounts
- weapon types
- level sistems
- user statistics (kills, conection time, last conection etc)
- caracter types

etc etc

For example: If you have a table in your base that handles weapons, you can simple add a record (with weapon name, weapon image, amunition, damage etc) without update your game and you have a new weapon in the game store :).
  • 0

#21 slam drago

slam drago

    The slam drag

  • New Member
  • 422 posts
  • Version:GM:Studio

Posted 26 September 2011 - 03:42 PM

Good tutorial! Thumbs up!
  • 0
My newest website. Check it out!
I support Cryset Games. Make money playing and making games!
(\__/)
(='.'=) This is Bunny. Copy and paste Bunny into your
(")_(") signature to help him gain world domination.
My avatar is best viewed in the lighter GMC theme.

#22 tomasart

tomasart

    GMC Member

  • GMC Member
  • 269 posts

Posted 26 September 2011 - 04:23 PM

You know how i can use the GMHTML5 built-in server tu run php files on local? Because the example runs only on my online server.
  • 0

#23 BlaXun

BlaXun

    Slime Online Creator

  • GMC Member
  • 2750 posts
  • Version:GM:Studio

Posted 26 September 2011 - 05:18 PM

set up a php-server ...Appache / XAMPP / WAMPP
  • 0

iBNKRoX.png


#24 tomasart

tomasart

    GMC Member

  • GMC Member
  • 269 posts

Posted 27 September 2011 - 07:41 AM

set up a php-server ...Appache / XAMPP / WAMPP


in the past i use "appserv" but this install phpmyadmin, apache etc etc. I ,dont need 20 services more running on my PC. Do you have a recomendation for me?
  • 0

#25 Sven

Sven

    GMC Member

  • GMC Member
  • 621 posts
  • Version:GM:Studio

Posted 28 September 2011 - 02:15 AM

set up a php-server ...Appache / XAMPP / WAMPP


in the past i use "appserv" but this install phpmyadmin, apache etc etc. I ,dont need 20 services more running on my PC. Do you have a recomendation for me?

If I'm just installing it on my home PC I use http://www.wampserver.com/en/
It's simple to use/modify and it lets you turn it off and on quite easily.
  • 0
I have a blog/site http://svenkle.com/

#26 tomasart

tomasart

    GMC Member

  • GMC Member
  • 269 posts

Posted 28 September 2011 - 04:39 PM

set up a php-server ...Appache / XAMPP / WAMPP


in the past i use "appserv" but this install phpmyadmin, apache etc etc. I ,dont need 20 services more running on my PC. Do you have a recomendation for me?

If I'm just installing it on my home PC I use http://www.wampserver.com/en/
It's simple to use/modify and it lets you turn it off and on quite easily.


Ok i have do it so. Online all works, on my localhost all works. But in runtime of GMHTML5 not work, give me error like 404. I think he cound't find the php.
  • 0

#27 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 30 September 2011 - 01:38 PM

Hm... after not checking the example in a few days, I half expected a million or two apples to be in the database.

Ok i have do it so. Online all works, on my localhost all works. But in runtime of GMHTML5 not work, give me error like 404. I think he cound't find the php.

If everything else is working correctly and it is actually displaying 404 errors in your HTML5 game, there's a good chance that it can't find the PHP. Use a message box and return the path of the PHP file the game is using and compare it to where it actually is.
  • 0
Posted ImagePosted Image

#28 FiLkAtA

FiLkAtA

    GMC Member

  • GMC Member
  • 541 posts
  • Version:GM:Studio

Posted 01 October 2011 - 03:01 PM

Would it be possible to use Gm , Javascript and php to make an web app that reads from and writes to a text file? I know I could do it with an database but I don't want to have to learn SQL and I'm looking to do this using as little Javascript and php as possible.
  • 0

#29 pedrosorio

pedrosorio

    GMC Member

  • GMC Member
  • 971 posts

Posted 01 October 2011 - 03:08 PM

Would it be possible to use Gm , Javascript and php to make an web app that reads from and writes to a text file? I know I could do it with an database but I don't want to have to learn SQL and I'm looking to do this using as little Javascript and php as possible.


If you can do it with a database, you can also do it with a text file. Just use this example's php and the file functions:

http://www.w3schools...hp/php_file.asp

http://www.w3schools..._filesystem.asp
  • 0
"Let's leave the classics for your parents." - KC LC

#30 FiLkAtA

FiLkAtA

    GMC Member

  • GMC Member
  • 541 posts
  • Version:GM:Studio

Posted 01 October 2011 - 03:25 PM

Did you mean Javascript instead of php? Cause the php in the example is for a database, something that I do not want to use.
  • 0

#31 BlaXun

BlaXun

    Slime Online Creator

  • GMC Member
  • 2750 posts
  • Version:GM:Studio

Posted 01 October 2011 - 03:56 PM

You canuse some php methods to read from files easily
  • 0

iBNKRoX.png


#32 pedrosorio

pedrosorio

    GMC Member

  • GMC Member
  • 971 posts

Posted 02 October 2011 - 12:14 AM

Did you mean Javascript instead of php? Cause the php in the example is for a database, something that I do not want to use.


I meant that you can use this example's php but use file instead of database functions to process the data it receives.

Edited by pedrosorio, 02 October 2011 - 12:14 AM.

  • 0
"Let's leave the classics for your parents." - KC LC

#33 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 05:04 AM

Nice!
But where do I put the javascript code? I really don't get AJAX, and I have no idea in what kind of file I have to put the AJAX code to get it to work.

Please help!
  • 0

#34 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 05:06 AM

AJAX isn't a language in itself, it's a programming technique implemented with JavaScript. So, I suppose to answer your question, you put the JavaScript in a JavaScript file and import it as an extension into GM:HTML5 as stated.
  • 0
Posted ImagePosted Image

#35 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 06:19 AM

AJAX isn't a language in itself, it's a programming technique implemented with JavaScript. So, I suppose to answer your question, you put the JavaScript in a JavaScript file and import it as an extension into GM:HTML5 as stated.

I did that now, added the extension and all, but it still doesn't work. It won't run my php file.
  • 0

#36 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 06:30 AM

Make sure it's all uploaded to a server. It won't work running on your local system.
  • 0
Posted ImagePosted Image

#37 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 06:46 AM

Make sure it's all uploaded to a server. It won't work running on your local system.

I found out that extensions don't work for me in general. No matter what I do, no extension ever does anything.
Maybe there's an update that fixes this somewhere, know any links?
  • 0

#38 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 07:37 AM

Well that could be a lot of things... it's almost definitely not GM-HTML5 since it works for everyone else; there's something that you aren't doing correctly. Give us more information.
  • 0
Posted ImagePosted Image

#39 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 07:57 AM

Well that could be a lot of things... it's almost definitely not GM-HTML5 since it works for everyone else; there's something that you aren't doing correctly. Give us more information.

Define more information, what do you want exactly?
  • 0

#40 tangibleLime

tangibleLime

    Lunatic

  • GMC Elder
  • 2520 posts
  • Version:GM:HTML5

Posted 10 October 2011 - 04:29 PM

Anything?
  • 0
Posted ImagePosted Image

#41 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 11 October 2011 - 04:59 AM

Okay:
OS: Windows 7 Ultimate Home Edition
My JS file: Alerted(argument0){alert(argument0);}
Function Defined: Fuction name: Alerted Help: Alerted(string)
Arguments: argument0 string

That help?
  • 0

#42 Schalk

Schalk

    GMC Member

  • GMC Member
  • 487 posts
  • Version:GM:HTML5

Posted 11 October 2011 - 06:52 AM

Try setting the External Name to "Alerted". If that doesn't work, try making your JS file: "Alerted(argument0){alert(argument0);return 0;}"
  • 0

Game Maker HTML5 Extensions
Mouse Extension | HTML Extension


#43 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 12 October 2011 - 07:21 AM

Try setting the External Name to "Alerted". If that doesn't work, try making your JS file: "Alerted(argument0){alert(argument0);return 0;}"

I did that too, didn't work at all.
  • 0

#44 Schalk

Schalk

    GMC Member

  • GMC Member
  • 487 posts
  • Version:GM:HTML5

Posted 12 October 2011 - 08:48 AM

Wait, is your code:

Alerted(argument0){alert(argument0);}

or

function Alerted(argument0){alert(argument0);}

Edited by Schalk, 12 October 2011 - 08:49 AM.

  • 0

Game Maker HTML5 Extensions
Mouse Extension | HTML Extension


#45 metaaldetectie

metaaldetectie

    GMC Member

  • New Member
  • 4 posts

Posted 21 October 2011 - 10:26 AM

an example/tutorial of a high score would be great and very useful. :thumbsup:
  • 0

#46 cerberus150

cerberus150

    GMC Member

  • New Member
  • 33 posts
  • Version:GM:HTML5

Posted 22 October 2011 - 07:20 AM

Wait, is your code:

Alerted(argument0){alert(argument0);}

or

function Alerted(argument0){alert(argument0);}

I did:
function Alerted(argument0){alert(argument0);}

  • 0

#47 JeffJ

JeffJ

    GMC Member

  • GMC Member
  • 527 posts
  • Version:GM:Studio

Posted 24 November 2011 - 02:12 AM

I'm using ASP.NET, C# and MSSQL. I am trying to "convert" this example to these languages, but it's proving troublesome, although I should believe it to be possible. Can anyone help me, please?

I'm working from the same principles; GM talks to the JS that then talks to an ASPX page (that ASPX has a codebehind file in which the SQL commands are) that then talks back to the JS that then talks back to GM.

This is my C# Page_Load:

            //SqlConnection conn;
            SqlCommand comm;

            string connectionString;
            connectionString = WebConfigurationManager.ConnectionStrings["MydbConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(connectionString);

            if (Request.QueryString["act"] == "getApples")
            {
                comm = new SqlCommand("SELECT * FROM apples", conn);

                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    string color = reader.GetString(1);    // Weight int
                    Response.Write(@"<script language='javascript'>alert('The color is: \n" + color + " .');</script>"); 
                }
                conn.Close();
            }

My updateApples() function looks like this:

// updateApples();
// retrieve the green and red apples from the database
global.applesGreen = string_parse(SQLCommand("Default.aspx?act=getApples&color=green",0),"|",true);
global.applesRed = string_parse(SQLCommand("Default.aspx?act=getApples&color=red",0),"|",true);

But it seems nothing is extracted from the database. I tried displaying the value of the getApples function, and it displays the entire ASPX site (all the tags and stuff), so it's retrieving something at least...

Could anyone please help me here?

Edited by Elminster, 24 November 2011 - 02:13 AM.

  • 0

spoileralertsignature.png     jefftwittersignature.png


#48 kburkhart84

kburkhart84

    Firehammer Games

  • GMC Member
  • 2026 posts
  • Version:GM:Studio

Posted 24 November 2011 - 06:16 PM

I have two things.

One, I don't recommend using a text file for something online very much. There is no locking/unlocking of the files guaranteed, and you could easily corrupt the file. Say you are in the middle of using it, and the player closes the browser. The file may not get closed properly. Say more than one player(by sheer chance, but more likely with more players at once) happen to want to access the file at the same time. Good luck with that. The mySQL database system handles all of that for you, automatically.

Two, besides installing a server/database on your test PC, is there an easy way to implement this into a game? I'm not interested in making sure this part works, rather I'd want the game to have no problems if I test it in windows or HTML5 mode here. I know it won't right as far as creating high scores etc... but I want to do it without changing code later. For example, maybe a call to the PHP related functions would return a specific error if PHP isn't available. The only thing I know right now is using the constants yoyo provides which would tell me if it is a windows or HTML5 build, but that won't tell me if PHP is available or not.
  • 0

My KBInput system is now on the marketplace here.  It wraps up nice and tight GMStudio's input system into a few function calls making a user configurable input system that works the same regardless of what inputs the player has chosen including keyboard, mouse buttons, and gamepad/joysticks using DInput/XInput.  The support forum topic for it is here.


#49 Timmo

Timmo

    GMC Member

  • New Member
  • 558 posts
  • Version:GM:HTML5

Posted 28 December 2011 - 03:37 AM

Hi! I messed with this tutorial for hours. I can get everything working except retrieving from the database. Gamemaker communicates with the script, but it returns nothing when i try to read the apples. I can return values before using the script but after i call the script i can't show any splash screens - the script returns ''. Anyone knows a fix? I am using the latest GM.1.0.187
  • 0

Posted Image Posted Image


#50 rater193

rater193

    GMC Member

  • GMC Member
  • 127 posts
  • Version:GM:Studio

Posted 10 September 2012 - 12:35 AM

GM-HTML 5 SQL Demo

With the advent of GM-HTML5, communicating with a MySQL database may prove an extremely useful resource for storing information. This is a simple guide to help you get started. For this example, we will be looking at a virtual basket of apples. Our database can hold a total of 16 apples - 8 green and 8 red.

If you're impatient or really don't care about how the process is done, check out the live example here.

Part 1 - Code

Step 0 - Basic Understanding of the Process

Like a lot of web development, this process will span multiple languages.

We will use GameMaker to execute a script from a JavaScript file. The JavaScript command loads a PHP file without reloading the page (AJAX). That PHP file has the ability to manipulate the MySQL database. After doing that, the PHP file can return data by displaying information needed to be returned. The JavaScript will accept that data and report it back to GameMaker.

This is not a guide for learning PHP, GML, JavaScript or SQL. It assumes that you have at least a basic understanding of all four languages. Without moderate PHP and SQL knowledge, manipulating the database may prove difficult. Refer to the PHP-MySQL guide at w3schools to learn more.

Step 1 - JavaScript

We will use JavaScript (AJAX) to execute a PHP file that contains the functions we wish to use. It returns the text that would be displayed on the PHP page if it was loaded by itself.

Parameters:
url - (String) Path to the PHP file with appended arguments.
async - (0 or 1) Run the command asynchronously (1) or synchronously (0).

function SQLCommand(url,async) {
   if (window.XMLHttpRequest) {
      xmlObject = new XMLHttpRequest();
   } else {
      xmlObject = new ActiveXObject("Microsoft.XMLHTTP");
   }
   
   xmlObject.open("GET",url,async);
   xmlObject.send(null);

   return xmlObject.responseText;
}

For the most part, you won't have to edit this function.

Step 2 - PHP

PHP will be used to actually speak with the MySQL database and carry out the desired actions. If a value is to be returned, the PHP function will simply echo the result onto the page, which the JavaScript function above will read and report back to GameMaker.

We'll start with two standard functions that we'll use to connect and close the connection to the database. I've removed the login information in my example for obvious reasons.

<?
   // database variables
   $dbHost = "localhost";
   $dbName = "<name here>";
   $dbUser = "<user here>";
   $dbPass = "<password here>";

   // database connection functions
   function dbConnect() {
      global $dbCon, $dbHost, $dbName, $dbUser, $dbPass;
      $dbCon = mysql_connect($dbHost,$dbUser,$dbPass);
      return mysql_select_db($dbName);
   }
   
   function dbClose() {
      global $dbCon, $dbHost, $dbName, $dbUser, $dbPass;
      mysql_close($dbCon);
      unset($dbCon);
   }
?>

Now need a table in the database, which is our virtual apple basket.

Our basket of apples will be a table consisting of three fields:
1) appleid (INT) - a unique identifier for the apple
2) color (TINYTEXT) - the apple color (green or red)
3) weight (INT) - the weight, in grams, of the apple

We can use PHP or phpMyAdmin to create the table. The following PHP code will suffice.

<?
   // connect to the database
   dbConnect();

   // create the table
   mysql_query("CREATE TABLE apples
      (
     	appleid int NOT NULL AUTO_INCREMENT,
     	PRIMARY KEY(appleid),
     	color TINYTEXT,
     	weight INT
      )
   ");

   // close the connection to the database
   dbClose();
?>

Now that we have a table to operate on and an easy way to connect to the database, we can define our custom functions. The PHP file accepts a standard argument, act, which decides which function to execute. Therefore, we have a switch statement that designates program control. Our example has three functions: Get apple lists, add an apple to a list and empty the entire basket.

<?
   // custom SQL functions
   switch($_GET['act']) {
      case "getApples":
     	dbConnect();
     	$qry = mysql_query("SELECT * FROM apples WHERE color='$_GET[color]'");
     	$compile = "";
     	while ($data = mysql_fetch_array($qry)) {
            if ($compile != "") $compile .= "|";
            $compile .= $data['weight'];
     	}
     	dbClose();
     	echo $compile;
     	
     	break;
      
      case "addApple":
     	dbConnect();
     	mysql_query("INSERT INTO apples VALUES ('','$_GET[color]','$_GET[weight]')");
     	dbClose();
     	
     	break;
      
      case "removeApples":
     	dbConnect();
     	mysql_query("TRUNCATE TABLE apples");
     	dbClose();
     	
     	break;
   }
?>

With the argument of "getApples", the PHP file will use the additional argument of "color" to return a list in the form "x|y|z|..." of the weights of all apples of that color. The "addApple" command will insert a new apple into the basket with the specified color. The "removeApples" command will simply truncate the table, emptying the basket completely. Notice how in order to return a value, we simply echo the information to display it on the page. Users never actually see this information - it is read by the JavaScript AJAX and returned to GameMaker.

Step 3 - GameMaker

Now that we have PHP to talk to the database and JavaScript to talk to the PHP, we need the GameMaker generated HTML5 to talk to the JavaScript. In a new GM-HTML5 project, we create a new extension that employs the use of the function we wrote in the beginning of the demonstration. Refer to this tutorial by JacksonYarr if you have difficulty with this step. Assign the name of the function SQLCommand with two arguments (string, double), and a string return type.

After we've imported the AJAX JavaScript function, we're essentially all set. Use the SQLCommand(url,async) function to load the PHP file with your desired parameters.

For our apple basket example, the logical first course of action is to create a script that updates the lists of green and red apples.

// updateApples();
// retrieve the green and red apples from the database
global.applesGreen = string_parse(SQLCommand("sql.php?act=getApples&color=green",0),"|",true);
global.applesRed = string_parse(SQLCommand("sql.php?act=getApples&color=red",0),"|",true);

I'm using the string_parse script from GMLScripts.com, which I will provide the source to at the bottom of this post. The string_parse function takes the returned list of "x|y|z|..." and converts it into a ds_list containing the elements {x, y, z, ... }, much like the explode function of PHP.

Let's take a closer look at how GameMaker is getting the lists from the database. In particular, the list of green apples.

We call SQLCommand("sql.php?act=getApples&color=green",0) to get the raw list of green apples. You can see from the URL, the argument act is set to the function getApples, and the argument color is set to green. Refer back to our PHP function to see how these arguments direct program flow. We have the async parameter set to 0 in order to have the program wait for the SQL statement to go through before our program continues.

To add an apple to the basket, we simply use the addApples function. Remember, we don't want the basket to have more than 8 apples of each kind.

// add a green apple with a random weight into the database
if (ds_list_size(global.applesGreen) > 7) {
   show_message("You can only have eight green apples at a time!");
} else {
   randomWeight = random_range(100,250);
   SQLCommand("sql.php?act=addApple&color=green&weight="+randomWeight,0);
}

// update the apple counts
updateApples();

This code adds a green apple to the database, for reasons that I hope are now perfectly clear. Afterwards, we update the lists again to account for the new apple.

The procedure to empty the basket follows the same steps as the other SQL commands.

Part 2 - Example

View a live version of this example here. Note that multiple people may be accessing the example, so if you add one apple and two appear, it is because a different user added another.

It appears that exporting an editable project is not completely functional. When that is fixed, I will upload the editable example.



it works :D thanks soooo much, i will now be able to do sooo much more :)
  • 0

Click this to find out what you are!

Posted Image