Posts tagged MySQL
QuickTip: asSQL Connection Problem with non-localhost hostname
Dec 12th
asSQL is just great. It’s an ActionScript 3.0 library for connecting AIR applications to MySQL databases and it works brilliantly – when it works! Recently i gave it a shot again after an utter failure the last time i tried it… The library seems to be a port of the Java implementation of connecting to MySQL (Connections, Statements, Fields, etc). It takes a little getting used to but it’s an excellent library and i highly recommend it.
Background
My development environment is Windows-based (against my wishes… not enough loot or motivation for a Mac, lack of Adobe software on Linux) but i make up for this by running a virtual Linux installation in my Windows environment and networking the two together. It actually works really well, and the process for setting this up can be found here. To cut a very long and boring story short, essentially i cannot use localhost as your server when using this architecture since i have my LAMPP stack running on my Linux environment, so my “local server” can only be accessed using the IP address of the virtual system.
This complicates things a bit when trying to use asSQL to connect to my MySQL installation, because MySQL gets all paranoid and won’t accept connections from a foreign IP address (the IP of my Windows machine on which my AIR app is running)… To get around this, all you have to do is create a new user in MySQL (i used phpMyAdmin), set the user’s hostname to the IP address of your remote system (i’ve explained how to do this below) and you’re ready to rock and roll!
Solution
The first thing you need to do is get the IP address of the remote system…
Windows: Open the command line, type ipconfig
Linux & Mac: Open the terminal, type ifconfig
In this example, my IP address is 192.168.56.1
I’ll be using phpMyAdmin to fix the problem.
- Open phpMyAdmin and click on the Privileges tab.
- Click Add a new User
- Enter any username you like, paste the IP address obtained in the Host field and put in a password
- Under the Database for user panel, leave it at None
- Under the Global privileges, you can Check All
That should sort it out… Remember, this is HIGHLY insecure and should only be used on development environments and NOT production environments.
Using Conditional Statements with MySQL
May 14th
While working on a project, i got lazy (as i always do…); I didn’t feel like fetching an array of rows from MySQL and filtering the data in PHP according to a condition… Too much of a ballache to be honest. I thought: ‘Fuck it… Let’s see if one can use conditional statements in MySQL‘.
After doing a little research, i came across this page (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html). After scouring through the normally indecipherable MySQL reference manual, i managed to get the hang of it…
Although the scenarios where the application of this functionality are few and far between, i felt it’d still be a cool idea to share this (seemingly) arbitrary tit-bit.
Consider the following scenario…
You have a table of users. In this table, you keep the following information about each user:
- name
- surname
- gender
Now, depending on the gender of your user, you would like to return their details with a certain prefix, namely Mr for a male or Ms for a female. Here’s the database structure, and two rows of sample data:
CREATE TABLE IF NOT EXISTS `users` ( `name` varchar(255) NOT NULL, `surname` varchar(255) NOT NULL, `gender` enum('M','F') NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC; -- -- Sample data -- INSERT INTO `users` (`name`, `surname`, `gender`) VALUES ('Joe', 'Shmo', 'M'), ('Jane', 'Shmane', 'F');
…and here’s the SQL query
SELECT *, CONCAT(IF(gender = "M", "Mr ", "Ms "), name, " ", surname) AS fullName FROM users
If that looks a little too indecipherable/complicated, here’s the previous query in a more simplified (albeit less efficient) way:
SELECT *, IF(gender = "M", CONCAT("Mr ", name, " ", surname), CONCAT("Ms ", name, " ", surname)) AS fullName FROM users
Essentially the IF() statement is structured like this:
IF(condition, true code, false code)
However, you can place an IF statement anywhere in a query (from what i can tell thus far), it gets executed in place and is replaced by either the true code or the false code.
Another (much simplified) example:
SELECT IF(1 > 0, "TRUE!", "FALSE!");
…and that’s conditionals with MySQL!
Using MySQL and JSON
Apr 25th
JSON has – over the past few months – start working its way more and more into my daily life as a web developer. I find myself using it for all sorts of solutions, whether i’m using ActionScript or PHP. For those of you who don’t know, JSON stands for JavaScript Object Notation. JSON is an extremely lightweight, human-readable and highly compacted data-interchange format. JSON works on the principle of name/value pairing, and it’s very easy to read, write and parse.
A typical JSON representation of the following PHP object would be:
{"title":"Using MySQL and JSON","date":"25 April 2009","timeOfWriting":"15h34"}
1 2 3 4 5 6 | <?php $blogPost = new stdClass(); $blogPost->title = "Using MySQL and JSON"; $blogPost->date = "25 April 2009"; $blogPost->timeOfWriting = "15h34"; ?> |
and the following ActionScript object would also be represented as it was above:
1 2 3 4 5 6 7 | var blogPost:Object = new Object(); blogPost.title = "Using MySQL and JSON"; blogPost.date = "25 April 2009"; blogPost.timeOfWriting = "15h34"; // -----or----- //var blogPost:Object = {title:"Using MySQL and JSON", date:"25 April 2009", timeOfWriting:"15h34"}; |
JSON can be extremely useful when you want to pass data from any platform to any other platform as the format is – essentially – just plain ol’ text and computers can parse JSON objects very easily.
In PHP5, this is supported natively, using the json_encode and json_decode functions.
However, in ActionScript 3.0, the parsing of JSON strings is not supported in the native ActionScript 3.0 API, so you can either write one yourself or use the JSONEncoder or JSONDecoder classes found in the as3corelib package.
Here’s how to encode/decode a JSON string in PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $blogPost = new stdClass(); $blogPost->title = "Using MySQL and JSON"; $blogPost->date = "25 April 2009"; $blogPost->timeOfWriting = "15h34"; // -----or----- // $blogPost = array("title" => "Using MySQL and JSON", // "date" => "25 April 2009", // "timeOfWriting" => "15h34"); $json = json_encode($blogPost); echo "Encoded JSON: ".$json; echo "<br/>Decoded JSON (as associative array):<br/>"; print_r(json_decode($json, true)); echo "<br/>Decoded JSON (as stdClass object):<br/>"; print_r(json_decode($json)); ?> |
…and in ActionScript 3.0 using the as3corelib package:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import mx.utils.ObjectUtil; import com.adobe.serialization.json.JSONDecoder; import com.adobe.serialization.json.JSONEncoder; var blogPost:Object = new Object(); blogPost.title = "Using MySQL and JSON"; blogPost.date = "25 April 2009"; blogPost.timeOfWriting = "15h34"; // -----or----- //var blogPost:Object = {title:"Using MySQL and JSON", date:"25 April 2009", timeOfWriting:"15h34"}; var json:String = new JSONEncoder(blogPost).getString() trace("Encoded JSON: " + json); trace("Decoded JSON: " + ObjectUtil.toString(new JSONDecoder(json).getValue())); |
Now that we’ve gotten that out of the way, let’s have a look at how we can use JSON inside of MySQL. First off, let me say that i’m a big fan of structuring one’s databases correctly and not taking hideous shortcuts like i’m about to show you, but sometimes doing this hideous shortcut might actually help you develop your appplications faster, and keep things extensible.
I’ve found that i often have to keep changing my database structure when clients have changes of heart (and man, do they change them often!). It becomes extremely frustrating to have to restructure an entire database (and all associated PHP/AS3 code) every time a client remembers that he forgot about needing to store something as ridiculous the big-toe girdths of his future website’s users.
Now, i’m certainly not a patient person, and – to be honest – i don’t have time to fuck about and keep changes logic just to accomodate menial extra pieces of info. What i do therefore is usually keep a settings column in the users table, set it’s type to Text and store JSON strings in there to keep track of all the silly idiosyncratic (and sometimes idiotic) requirements of the client. Then all i have to do is parse out that string and apply some business logic to the values i find in that row under the settings column.
I find that it makes things a lot simpler and with orders of magnitude less ballaches.
What do you think?
Using PHP to Backup and Save your MySQL Database
Apr 17th
While working on a recent project, i needed to set up a cron job that would run every X amount of hours and backup a database. I’ve done this a few times before, but only this time (while Googling for a better solution) i found David Walsh‘s blog post on how to Backup Your MySQL Database Using PHP. David’s done a great job and i definitely recommend you check his blog out in its entireity for some really neat web dev articles.
I decided to go and put David’s script into class form (my case of OCD is genuine
) and i added one or two things to it. Basically it allows you to backup one or many tables in a database, include or exclude the data from the backup and i also included Rick Ellis’ (of CodeIgniter fame) Zip class to allow you to zip up the backup and stash it somewhere.
Thanks to David Walsh and Rick Ellis!
Here’s the class: DatabaseDump.php
…and here’s how to use it:
$dump = new DatabaseDump("host", "user", "password", "database", "destination/"); $dump->backup();
Be sure to check out the DatabaseDump.php class for the documentation!
Working with LAMPP on Linux Mint
Jan 26th
Following from my previous post, i decided to try and mimick my development environment at work on my laptop. The quickest and easiest way to do this is to install XAMPP for Linux. The folks over at apachefriends have given us one of the greatest gifts a web-developer geek could want… A pre-configured, fully open and customizable, versatile setup of LAMPP (Linux, Apache, MySQL, PHP and Perl). Here’s what the package includes:
Apache 2.2.11, MySQL 5.1.30, PHP 5.2.8 & PEAR + SQLite 2.8.17/3.3.17 + multibyte (mbstring) support, Perl 5.10.0, ProFTPD 1.3.1, phpMyAdmin 3.1.1, OpenSSL 0.9.8i, GD 2.0.1, Freetype2 2.1.7, libjpeg 6b, libpng 1.2.12, gdbm 1.8.0, zlib 1.2.3, expat 1.2, Sablotron 1.0, libxml 2.7.2, Ming 0.3, Webalizer 2.01, pdf class 009e, ncurses 5.3, mod_perl 2.0.4, FreeTDS 0.63, gettext 0.11.5, IMAP C-Client 2004e, OpenLDAP (client) 2.3.11, mcrypt 2.5.7, mhash 0.8.18, eAccelerator 0.9.5.3, cURL 7.19.2, libxslt 1.1.8, phpSQLiteAdmin 0.2, libapreq 2.08, FPDF 1.6, XAMPP Control Panel 0.6, bzip 1.0.5, PBXT 1.0.07-rc
Now stick that in your pipe and serve it!
This package must NOT be used on production server. NEVER! Please view this page for information about LAMPP’s inherent security flaws and why it benefits you on a local machine, but not on a production server.
The LAMPP package is simple enough to install, but there is one thing i noticed that is a bit of a ball-ache… By default, you cannot use LAMPP without an active internet connection. However, there is a quick fix:
- Open the httpd.conf file (sudo nano /path/to/httpd.conf)
- Look for the line that says Listen 80
- Change the line to Listen 127.0.0.1:80
- Save the file and restart apache
- Run http://localhost
- It works!