Mysql support for Rgss

Mysql support for Rgss
Version: 1.0
By: Berka


Introduction
This script allows you to connect to a mysql server with rgss.
Please read carefully the instructions in the script.

Screenshots
Not needed

Script

script Spoiler
  1. #======================================================================
  2. #                                                                   Net::Mysql
  3. #      29-05-2010                            www.rpgmakervx-fr.com                                  Rgss1&2  v.1
  4. #                                                                    par berka                 
  5. #--------------------------------------------------------------------------------------------------------------
  6. # This script is free to use. Do not post anywhere without my permission. Credits needed.
  7. #--------------------------------------------------------------------------------------------------------------
  8. # Warning: if your game is cracked and decrypted, your mysql login will be available !
  9. # Do not use with a database containing personal information.
  10. # Your mysql host should accept external connections.
  11. # Check with it for remote SSH access to your database.
  12. #--------------------------------------------------------------------------------------------------------------
  13. # This script allows interractions with a mysql database directly in the game
  14. # It requires a file "libmysql.dll" in the game folder
  15. #--------------------------------------------------------------------------------------------------------------
  16. # Attention: en cas de décryptage de votre jeu, vos identifiants mysql seront accessibles !
  17. #  Ne pas utiliser de base de donnée contenant des informations personnelles.
  18. #  Votre hébergeur Mysql doit accepter les connexions mysql externes.
  19. #  Vérifiez auprès de lui que vous avec un accès distant SSH à votre base de données.
  20. #--------------------------------------------------------------------------------------------------------------------------
  21. # Ce script permet d'interragir avec une base de données mysql directement via le jeu.
  22. # Il nécessite un fichier "libmysql.dll" à placer dans le dossier du jeu.
  23. #--------------------------------------------------------------------------------------------------------------------------
  24. #  — md5() support
  25. #  — Mysql functions:
  26. #   - Net::Mysql.new([host,user,pass,base,port]) : return : mysql connection handle
  27. #   - @mysql.close : return : bool
  28. #   - @mysql.list_tables([filter]) : return : ["table1", "table2"]
  29. #   - @mysql.select_db(base_name) : return : true if the db exists or false
  30. #   - @mysql.query("query",ret=false) : return : if ret = true : rows else result handle
  31. #   - @mysql.get_fields([handle result]) : return : ["field1", "field2"]
  32. #   - @mysql.get_rows([handle result]) : return : [["l1 row1", "l1 row2"], ["l2 row1", "l2 row2"]]
  33. #   - @mysql.fetch_assoc : return : {"field" => ["row1", "row2"] }
  34. #   - @mysql.num_rows([handle result]) : return : integer
  35. #  — Html functions:
  36. #   - "string".to_ruby : return : true, false, nil, Integer, Float, self, etc.
  37. #   - "<berka>".htmlspecialchars : return : "&lr;berka&gt;"
  38. #   - "<berka>".urlencode : return : "%3Cberka%3E"
  39. #   - "%3Cberka%3E".urldecode : return : "<berka>"
  40. #--------------------------------------------------------------------------------------------------------------------------
  41. # SQL queries samples
  42. #  —  "SELECT * FROM table"
  43. #  —  "INSERT INTO table (fields) VALUES (values)"
  44. #  —  "INSERT INTO table SET field = value WHERE field = value"
  45. #  —  "UPDATE table SET field = value WHERE field = value"
  46. #--------------------------------------------------------------------------------------------------------------------------
  47. # Sample :
  48. # @mysql = Net::Mysql.new
  49. # @mysql.query("SELECT * FROM `members`)
  50. # res = @mysql.fetch_assoc
  51. # => {:id=>["1","2"], :nom=>["berka","rgss"], :age=>["19",""]}
  52. #======================================================================
  53.  
  54. module Berka
  55.   module Mysql
  56.     Host   = "127.0.0.1"                          # mysql server(local : 127.0.0.1)
  57.     User   = ""                                        # mysql user
  58.     Pass  = ""                                         # mysql password
  59.     Base  = "rgss"                                 # base name
  60.     Port    = 3306                                   # server port (default: 3306)
  61.    
  62.     Err_Con = "Mysql:\nUnable to connect to the database"
  63.     Err_Req = "Mysql:\nUnable to send the query"
  64.   end
  65.  
  66.   module Html
  67.     Spec_Char=["$","&","+",",","/",";",":","=","@","?"," ","<",">","#","%","{","}","|","\\","^","~","[","]","`"]
  68.   end
  69. end
  70.  
  71. class Numeric
  72.   def copymem(len)
  73.     # move memory to convert c structs to ruby objects
  74.     Win32API.new("kernel32", "RtlMoveMemory", "ppl", "").call(buf="\0"*len,self,len);buf
  75.   end
  76. end
  77.  
  78. class String
  79.  
  80.   def to_ruby
  81.     # detect if the string is a md5 hash
  82.     return self if self=~/^[a-f0-9]{32}$/
  83.     # converts syntax of a string to ruby controls
  84.     eval(self)rescue self
  85.   end
  86.  
  87.   def htmlspecialchars
  88.     # converts special chars to html compatibles chars (ASCII)
  89.     {"&"=>"&amp;",'"'=>"&quot;","'"=>"&rsquo;","<"=>"&lr;",">"=>"&gt;"}.each_pair{|k,v|self.gsub!(k,v)}
  90.     self
  91.   end
  92.    
  93.   def urlencode
  94.     # converts special char of url
  95.     o="";self.scan(/./).each{|c|c="%"+c.unpack('H*')[0]if Berka::Html::Spec_Char.include?(c);o<<c};o
  96.   end
  97.    
  98.   def urldecode
  99.     # converts encoded special char of url to normal chars
  100.     self.gsub!(/\%(\w\w)/){|c|c.gsub!("%","").hex.chr}
  101.   end
  102. end
  103.  
  104. module Net
  105.   class Mysql
  106.     MI=Win32API.new("libmysql.dll","mysql_init","l","l")
  107.     MC=Win32API.new("libmysql.dll","mysql_close","l","l")
  108.     MQ=Win32API.new("libmysql.dll","mysql_query","lp","l")
  109.     MLT=Win32API.new("libmysql.dll","mysql_list_tables","lp","l")
  110.     MFL=Win32API.new("libmysql.dll","mysql_fetch_lengths","p","l")
  111.     MFR=Win32API.new("libmysql.dll","mysql_fetch_row","p","l")
  112.     MNF=Win32API.new("libmysql.dll","mysql_num_fields","p","l")
  113.     MFC=Win32API.new("libmysql.dll","mysql_field_count","p","l")
  114.     MSR=Win32API.new("libmysql.dll","mysql_store_result","l","l")
  115.     MRC=Win32API.new("libmysql.dll","mysql_real_connect","lpppplpl","l")
  116.     MNR=Win32API.new("libmysql.dll","mysql_num_rows","p","l")
  117.     MFFD=Win32API.new("libmysql.dll","mysql_fetch_field_direct","pi","l")
  118.     MFRE=Win32API.new("libmysql.dll","mysql_free_result","p","l")
  119.     MSDB=Win32API.new("libmysql.dll","mysql_select_db","p","l")
  120.    
  121.     attr_reader :handle
  122.    
  123.     def initialize(h=Berka::Mysql::Host,u=Berka::Mysql::User,p=Berka::Mysql::Pass,b=Berka::Mysql::Base,po=Berka::Mysql::Port)
  124.       # @handle : handle of mysql initialization
  125.       @handle=MI.call(0)
  126.       # establishes the mysql connection
  127.       (print(Berka::Mysql::Err_Con))if MRC.call(@handle,h,u,p,b,po,nil,0)==0
  128.       # returns: handle
  129.       @handle
  130.     end
  131.    
  132.     def close
  133.       # closes the current connection
  134.       MC.call(@handle)
  135.     end
  136.    
  137.     def select_db(base)
  138.       # selects a current database
  139.       MSDB.call(base)==true
  140.     end
  141.    
  142.     def list_tables(m="")
  143.       # lists tables request -> fetch the result -> to ruby string
  144.       l=MFR.call(MLT.call(@my,m)).copymem(1024)
  145.       # splits the string to array -> list of tables
  146.       l.scan(/\t(\w+)\0/).flatten
  147.     end
  148.    
  149.     def query(req,ret=false)
  150.       # sends the query (msg error)
  151.       (return print(Berka::Mysql::Err_Req+req))if !MQ.call(@handle,req)
  152.       # previous results are released
  153.       MFRE.call(@result)if @result
  154.       # gets the results from the query -> c struct handle
  155.       @result=MSR.call(@handle)
  156.       ret ? get_rows(@result) : @result
  157.     end
  158.    
  159.     # Proc: gets the name of the field (cstruct) -> to ruby string of handles -> to ruby string
  160.     # returns the fieldname or nil if the field is not found.
  161.     ReadField=Proc.new{|r,i,of|MFFD.call(r,i).copymem(1024).unpack("iissi")[0].copymem(of).delete!("\0")}
  162.    
  163.     def get_fields(res=nil)
  164.       # if a result handle is provided
  165.       r=res.nil? ? @result : res
  166.       # gets the number of fields, offset: 8bytes-2 (cf. loop)
  167.       nf,ch,of=MFC.call(@handle),[],6
  168.       # each field: if the fieldname is not found: increase the offset of bytes.
  169.       nf.times{|i|a=ReadField.call(r,i,of+=2)until a
  170.         # add to the fields array
  171.         ch<<a
  172.         # reinitialize the offset for the next iteration
  173.         of=6}
  174.       # returns an array of fields
  175.       ch
  176.     end
  177.    
  178.     def get_rows(res=nil)
  179.       # if a result handle is provided
  180.       r=res.nil? ? @result : res
  181.       # nr: number of rows, nf: number of fields
  182.       nr,nf,en=MNR.call(r),MNF.call(r),[]
  183.       # each row:
  184.       nr.times{|i|
  185.        # gets each row: c struct -> to ruby string -> to array (handles)
  186.        c=MFR.call(r).copymem(4).unpack("i")[0]
  187.        # gets each field length: c struct -> to ruby string -> to array (handles)
  188.        tf=MFL.call(r).copymem(4*nf).unpack("i*")
  189.        # size of field: offset of each field
  190.        sf=tf.inject(0){|n,i|n+i}
  191.        # handle of row -> to string (offset) -> to array
  192.        en<<c.copymem(sf+nf).split("\0")
  193.        }
  194.        # returns each row as an array
  195.       en
  196.     end
  197.    
  198.     def num_rows(res=nil)
  199.       # if a result handle is provided
  200.       r=res.nil? ? @result : res
  201.       # returns: number of rows
  202.       MNR.call(r)
  203.     end
  204.    
  205.     def fetch_assoc(to_ruby=false)
  206.       # gets rows and fields
  207.       h,f,r={},get_fields,get_rows
  208.       # each field: read the rows and store them to an hash : h[:field]=[rows]
  209.       # rows are converted to ruby objects if to_ruby == true
  210.       f.each_with_index{|fi,i|t=[];r.each{|l|t<<l[i]};h[fi.to_sym]=(to_ruby ? t.map!{|o|o.to_ruby if o} : t)}
  211.       h
  212.     end
  213.   end
  214. end
Expand to see the code.


Instructions

Paste this script above main. This script works with RMXP and RMVX
Add this file: libmysql.dll in your project's root.
Mediafire: libmysql.dll

FAQ
- the script does not work:
-> check for the remote SSH access with your webhost. Please test first in localhost.
-> your query may have syntax errors
- the script takes time to run:
-> the result of your query is too big
-> your server may be overloaded

Compatibility
No issues I guess

Credits and Thanks
The mysql team
French testers

Terms and Conditions
[color="#FF4000"]This script is free to use. Do not post anywhere without my permission. Credits needed.[/color]

Enjoy.

Berka
I must say, this script certainly looks impressive. While I don't have a MySQL server handy to test it (mine are all in use), if this works, it would be quite a big step in the right direction for the RM* community. The coding on this looks well done, although variable names could have been designed a bit better in some cases. Another point I found a bit lacking was comments. Specifically, the general lack of comments throughout the script. While most of the methods are short, they are not self-explanatory, and comments allow people to understand what it happening in the script.
Thanks !
I hate commenting my code. But I'll do it in the future release.
You could test the script with a wamp server.

Edit:
Woops escaped html characters have been converted...
{"&"=>"&*#38;",'"'=>"&*#34","'"=>"&*#39;","<"=>"&*#60;",">"=>"&*#62"}
(remove the *)
Instead of doing that, try clicking the checkbox for "Do not automatically parse URLs". When I do that, I get this:
{"&"=>"&#38;",'"'=>"&#34","'"=>"&#39;","<"=>"&#60;",">"=>"&#62"}
Thank you !
Well, if you know mysql functions I have forgotten there, please tell me.

damn... my english is quite bad... sorry.
The script really looks short and crisp... you could work on your coding style, but yeah... who cannot ^^
This script should prove really useful and, in the right hands, could spawn some incredible network-using games. Thanks for sharing (free of charge)!

In terms of improvement suggestions... having a basic handler that connects and closes upon implementation of this script would heavily descrease the amount of nerdness/expertise needed to use this script (even though it's not too much trouble really... but you'd be surprised how big of a difference just a bit of aid to the user makes). Providing users with a basic way of accessing the database (aka allowing them to just use get_rows after putting in their server data without needing to setup anything further) has a number of advantages:
- improved compatibility between games developed with this system
- getting rid of the in-theory unneeded step of creating the connection step yourself
- way less advanced to use, as it basically just adds database functionality
- will detract less users from using it because of the complexicity level

I also wonder if you knew about the MySQL script for RMXP, and if so, your assumptions on performance differences (unfortunately, I can't seem to locate the script anymore, I only remember I had it saved on this PC ages ago...).


I heavily disapprove of the topic tag though... while you sure are proud of your work, the topic really asks for the RMVX badge, especially since you never note it anywhere else... remember: Just because some .org admins have been smoking crack and put badges like this one in doesn't mean you have to use it ;)
Also, your server IP line misses a dot at the local example in the comment at the end of the line.

Other than that, I'm waiting for the first person to ask for a demo... :haha:
Thank you for advice.
I've seen the rmxp mysql script. But the concept is too complexe: it uses the Socket and the Network classes.
Sockets are quite a bad way for connections. However mysql connections are short and frequent. But I have done no benchmark.
For the "nerdness" requirement I don't really know. This script is done for programmers. And I think everybody who has coded a website knows how mysql runs. In addition get_row and get_fields work alone:
  1. hwnd = Net::Mysql.connect
  2. Net::Mysql.query("SELECT * FROM `members`)
  3. res = Net::Mysql.get_rows(hwnd)
  4. => [["l1 row1", "l1 row2"], ["l2 row1", "l2 row2"]]
  5. Net::Mysql.close(hwnd)
Expand to see the code.


About the demo. Well I'll do it. I'll add more comments too.
regards,

berka

ps. I changed the topic tag. Thanks
The demo thing was meant as a pun, as it'd require a password in the script to work, and that'd be... well ^^

And yeah, I remember it to be quite complex, however I had no idea it really had additional classes in use... At the time, I wasn't really doing anything with web stuff, so I merely saved it for later use and now lost it... ^^"
New version released:

- Mysql class
- select_db
- minor bugs fixed
- comments added
I really like the changes and comments! Keep up the good work!
The main thing that kills it for me is being able to see the MySQL details in the file. It's one thing to be able to URL hack an entry to fake a highscore or something, but another thing entirely to be able to edit anybody's info or even drop the whole database by decrypting a program, no matter how hard or easy it is to decrypt.

Nonetheless, this is a great script, and easy to get working.
Thanks ! I think there will always be cheaters and dishonest people. I trust people. If they are smart enough, they will watch the source code and respect your work. If they cheat, too bad for them ... They are bullies. They are wasting their time. The most skilled hackers will respect your job.

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=71040