Wednesday, July 18, 2012

Simple PHP loop script to transfer user table

A while back I was working on my CodeIgniter project and decided to restructure my database. Since I didn't have many rows that actually mattered (it was all test data), the only thing I needed to transfer over was my user table. So here's a simple example of a script that will transfer records over from one database to another.


<?php

// Set the connection information
$con = mysql_connect("localhost", "root", "root");

// Select the original database containing old records
mysql_select_db("old_db", $con);

// Check the connection
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Select the records from the database
$query = "SELECT * FROM user_table";

// Run the query
$result = mysql_query($query);

// Now select the new database
mysql_select_db("new_db", $con);

// Loop through each row from the old database
while ($row = mysql_fetch_assoc($result))
{

     // Set each column to a variable
     $user_name = $row['user_name'];
     $password = $row['password'];
     $email = $row['email'];
     // You could also reset defaults or check for NULL columns

     // Here's an example for permissions:
     if ($row['permissions'] == 0)
     {
          $permissions = 1;
     }
     else if ($row['permissions'] > 3)
     {
          $permissions = $row['permissions'] + 1;
     }
     else
     {
          $permissions = $row['permissions'];
     }
     $date = $row['date'];

     // Set up the INSERT query
     $insert = "INSERT INTO new_user_table (user_name, password, email, permissions, date) VALUES ('$user_name', '$password', '$email', '$permissions', '$date')";



     // Run the INSERT query
     mysql_query($insert);


     // Check to make sure this particular INSERT worked
     if (!mysql_insert_id())
     {
          echo "ERROR: there was a problem inserting data.";
     }
}

// Close the connection
mysql_close($con);

?>

That's it! This script is pretty simple and might not be great for really large user tables, but for smaller sites or when you're just testing data, it works fine.

Friday, July 13, 2012

Using CRON and PHP scripts with Dreamhost

As a followup to my previous post regarding inserting RSS feed data into a MySQL database, I wanted to quickly explain how I used DreamHost's CRON to create an automated news feed.

First make sure you have a script ready to use. Something that you want to run at certain time intervals. This could be the RSS feed script from before, something that scans user accounts, looks at site data and publishes an XML document, whatever. Just make sure it works (connects to DB, grabs or modifies data without problems, and closes the connection). Also be sure to change any local settings. For instance, if your script still says "localhost" for the connection string, it's not going to work!

Next we need to set up a Shell account, which is really easy in DreamHost:




It may take a few minutes for the new user to be created. After it's done, FTP into your web server using the new Shell account. I use Filezilla for this. If you don't know how to FTP in or setup Filezilla, this guide will probably help (or just Google it). Once you're in, create a folder called "cron" (or whatever you want to name it) and upload your scripts.




Almost done. Head back to DreamHost and click on "Cron Jobs", then "Add New Cron Job".



Finally we need to enter the cron settings. Select the shell user account you just created and title this cron job whatever you'd like. For "email output to", optionally enter an email address. If you do this, it will email you the results of your script. For instance, if you wrote your script in PHP and had any echo statements, you'll receive them. This is handy for when you first test your cron job so you can check that each part is running successfully. For example, you may want to echo/output any possible errors, success messages for DB connections/inserts/selects/etc., and a message at the end saying "script successful" or "script failed". After a few successful iterations of the cron job you can turn it off if you please.


For status we obviously want it enabled, although you can disable it later if you deem this script unnecessary. I prefer this as opposed to deleting it in case you want it later. For the command, we enter the path to the script. You can also write command code here, but I prefer having an external script I can modify and play with. I also leave locking on. And lastly, you can set your cron interval. This particular script runs every 15 minutes since I need fresh news frequently.




And that should be it. Once you submit it the cron job will run at the next interval and hopefully the script will execute successfully! For me, this allows me to read incoming RSS feeds, insert it into the DB, and then use the data on my website. It works great and I haven't had any problems since implementation. Good luck!


UPDATE: that space between php and /home/ in the command is on purpose! Be sure to do the same.

Tuesday, March 20, 2012

Running an eSports Booth

The other weekend I was in the Twin Cities (MN) for a Teh Pwn Gaming / CSL StarCraft 2 tournament (you can read about it here). It was a ton of fun and I wanted to share a particular aspect about it that might be of interest to some young entrepreneurs out there. Here's what I learned about running an event booth.

The story begins on Facebook. I was contacted by my friend Evva, the president of Teh Pwn, and she asked me if I wanted a booth for the up-coming event. I was initially concerned about agreeing because my operation is small, obscure, and the opposite of well-funded (one of those grassroots, indie-style operations). Anyways, I pictured myself next to Antec, ASUS, and NOS whose booths were epic, decked out with kick-ass banners and voluptuous women distributing tons of free swag. Needless to say I was afraid of looking inadequate and cheap. But Evva assured me that everything would be fine and it was a great opportunity to network and share my website. So I agreed.

To prepare I ordered business cards, spray-painted some t-shirts, and packed my laptop. It was a pretty low-key package, but figured it would do. However, upon arrival I checked out my setup and realized I forgot some sort of banner. Oops... But we ended up making a banner out of cardboard paper which looked pretty legit from a distance. If you do this, make sure it's cool within your industry. Fortunately eSports is pretty young so I don't think it was a big deal.

The best part about my setup was probably the business cards. I would highly recommend getting some. Why? Because you can get a ton of them for relatively cheap and you'll always have something to give out. If you just bring t-shirts, what happens after they're all gone? Now there's nothing for people to look at later and be reminded of your organization. Definitely order some.

Bringing a laptop was another great idea. It helped to physically show my site rather than just explaining it. If you don't have one, find someone who does and borrow it. If you're in technology, Internet, web, whatever, you need a device to show off your work.

One thing I wish I would have done differently is buy professionally made t-shirts. The ones we were wearing looked legit from a distance, but up-close looked cheap. I also wish we would have had some extras to give out. The NOS booth ran through all their free stuff right away because people wanted it. And in exchange they Liked them on Facebook and checked in on Foursquare. Not a bad deal in my opinion.

Overall, if you're thinking about representing yourself at an event. The more professional you can be the better. I'm unfortunately locked down by a small budget so I have to pick and choose, but if you're not, definitely get everything made professionally. A nice banner, solid business cards, free t-shirts, and a laptop will go a long way. But even if you can't do that, just go anyways. I still ended up meeting a ton of cool people and networked with other organizations. Don't doubt yourself, it'll be fun and everyone is a lot nicer and more supportive than you think.

Monday, February 13, 2012

Website Plugs February 2012

I wanted to give a shoutout to a couple websites that have really helped me in various fields of my life.

The first is a website analysis tool I stumbled on during spawnroom.com development last month. It's called WooRank.com. The reason I was so attracted to this site over others was their layout and simplicity. I entered my address, a little dial racked up points, and it told me exactly what to do to increase SEO. If you haven't tried it out, give it a whirl and see what you think. The test takes under a minute.

Next up is Astrid.com, a to-do list manager with apps for mobile devices. For awhile before Christmas I was looking for a website like this to manage all my projects and tasks, but hadn't come across anything spectacular. Most other sites were missing a crucial feature or just looked awful. But Astrid was simple, sleek and had everything I needed. Now I use it everyday and it has helped my productivity immensely. I definitely recommend testing it out.

Just for fun I wanted to shoutout Sputnikmusic.com. I've been using their site for a year or so and love it. Their album reviews are generally spot on and have helped me discover tons of new music. They also track your ratings so you can refer back and listen to great albums you forgot about. The only problem with their site is stability and speed. It seems to be down quite a bit and very slow at times.

Finally I wanted to shoutout my new site that I mentioned above: spawnroom.com. It's a major work in progress, but something I'm extremely excited about. It's an eSports resource website that will act as a centralized database of eSports knowledge. I have a ton of features I'm working on and will be releasing them over the next few months. Check it out and let me know what you think!

Note: I was not paid or asked to shoutout these sites. I'm doing this entirely on my own because I truly use and enjoy these websites.

Ways I manage my productivity

I'm currently in the process of starting a small business and I wanted to share the different ways I help improve productivity using online tools. I'd also love to hear recommendations from readers for new tools they find useful.

The first and most used tool in my inventory is Google Documents. I use docs for almost everything I write down because it's convenient, easy to use, and is safely backed up on a Google server. It's also attached to a Google account I use other services with like Gmail, Calendar, and Talk so this makes it even more useful.

The next best productivity tool I've discovered is Astrid to-do lists. This website and mobile app allows you to create categories, add tasks, schedule due dates, share them with coworkers, and set their priority. It's simple, easy to use, and best of all keeps me on track. I used this extensively for managing not only project development, but in my personal life as well. Easily one of the best, if not the best, to-do list I've ever used.

Next is duo of productivity tools that work amazing in conjunction with each other: Keepass Password Safe and Dropbox. To set this up, there are a few easy steps:

  1. Register for a Dropbox account and download the installer for your operating system.
  2. Install Dropbox and login with your account.
  3. Install Keepass, create a password database and save it in the Dropbox folder.
  4. Voilà! Your Keepass database should sync to your Dropbox account and any computer with the same login credentials.
This combo between Keepass and Dropbox has been amazing for me. My passwords are safe, in a centralized location, searchable AND backed up online and to other computers automatically. I highly recommend this setup so you can sleep easy at night.

Branching off this same idea, I also wanted to encourage readers to save other important documents there as well. Every night after I complete revisions to my projects I zip and copy them to the Dropbox folder. That way if my laptop was stolen or destroyed, I always have an updated copy of my work online and on my desktop. If you're concerned about the security of these files, you can take additional steps to protect them using TrueCrypt.
I won't go into too much detail here since there are plenty of tutorials online, but using TrueCrypt, you can encrypt files or create "containers" to place files in. This way you can encrypt your work and then back it up to Dropbox. This should definitely put any anxiety to rest.

For the last part I wanted to mention a couple other tools I use here and there. Twitter has been great for not only spreading awareness, but reminding myself of cool websites, ideas, and people. When I tweet, I am often times doing it for myself, just as much as for my followers. They also have the list feature which makes it easy to organize others into meaningful groups to reference later.
Google Calendar is another great application that helps me keep track of upcoming tasks and appointments, but is quickly being replaced with Astrid. Sorry Google!
The last one isn't exactly related to productivity but something I wanted to mention anyways. It's YouTube and their queue/playlist feature. I am involved in the eSports world with my website spawnroom.com and part of my job everyday is to follow the community by reading news and watching eSport podcasts and shows. The YouTube playlist feature is awesome for this. I grab the list of shows, hit up their VODs and launch the playlist. Works perfectly and keeps me up-to-date. Now I just wish all these shows used YouTube. Darn you OneMoreGame.tv!!!

Wednesday, January 18, 2012

Hosting a Mumble server with DynDNS on Windows 7

Last week my Mumble host decided to shutdown operations completely unannounced. Which was just awesome...but that aside I decided to try and host a server myself. Here's how I got it working on a dedicated Windows 7 box.

First, download and install Mumble. The server software, called Murmur is inside (something that wasn't obvious when I started). Install it and select the packages you want, Murmur for sure, Mumble if you want.

Once that's ready, head on over to DynDNS and setup an account. Once you've activated it, click on "My Services".

On that page, click "Add Hostname", and run through their process. This used to be free (no credit card), but it appears they require it now-a-days. After activation, simply cancel your order within 14-days and you won't be billed, but you keep your hostname. For this I selected spawnroom.dyndns.org.


Continuing with DynDNS, make sure to download the client updater and install it on the machine hosting the Mumble server. The client looks like this once you login and synchronize:


Alright, so we have Murmur installed and DynDNS installed. Next we need to configure the "murmur.ini" file. There's quite a few settings in here, but the main ones you'll want to look into are these:

welcometext=The text I want to welcome someone with when they join my server! HTML can be used here.
port=64738 or whatever port you want to use for the server. This can be whatever you like, however make sure it's something you're not already using. You can find out what ports you're using by opening a command prompt and typing "netstat". Browse the listed ports and select something NOT listed.
#host=Keep this commented out so the server will bind to all available connections.
serverpassword=Set a password here if you don't want "randoms" joining without the password.
users=20 or whatever number of user slots you want. This will vary depending on your bandwidth. For my 20 mbps business line I have ran 10 concurrent users with no noticeable lag. I'll try and update this post in the future with more information about what I am able to handle.
registerName=My Mumble Server or whatever you want the main channel of your Mumble server to be called. This is generally what people associate with the actual name of the server. So for my website, my main channel name is The Spawn Room.

This is all I changed in the ini. If you want to mess with other settings look at the Mumble documentation for more information.

Note: make sure to double check if a line has the # sign. If it does, that means it's commented out and won't work!

Now let's make a SuperUser password before moving on. Open a command prompt and enter:

<path to murmur.exe> -ini <path to configuration file> -supw <password>

This is how mine looked:

"c:\Program Files <x86>\Mumble\murmur.exe" -ini "c:\Program Files <x86>\Mumble\murmur.ini" -supw mySuperUserPassword

Note: the quotes are needed this time.



Port forwarding time! I'm not actually going to go into detail here because everyone has different routers, but here's the general concept. You'll want to log into your router which is probably at an address like: 192.168.0.1 or 192.168.1.1. If you've never logged in before, the default username and password can be found through Google with a search like "my router name/model default password".

Once you've successfully logged in, find a section for Port Forwarding. Now you'll need to add an entry for Mumble/Murmur (name it whatever you like), with the appropriate information. IP of the machine (command prompt -> ipconfig /all -> 192.168.x.x), the port (or port range) you selected for the Murmur server, and whatever else it asks for.


Again, depending on your router, you may need to restart to apply the settings. Do this now.

Once you're back up and running, it's time to launch the Murmur server and see if everything's working. Find murmur.exe in your Mumble folder, launch it and right-click the icon in the taskbar. Select "Show Log".


If you get "Server listening on 0.0.0.0" that's fine. I thought this meant it wasn't working, but it does. If you're getting an IP with "failed: The address is not available" after it, then it's NOT working. Or at least it wasn't working for me. I tried changing the port and ensuring that the #host= line was commented out.

Another important note here is that, for whatever reason, I was ONLY able to connect over LAN. Trying to connect to my DynDNS IP from the local network DID NOT work. If anyone knows why, I would love to hear it. But for those of you just trying to get this working, don't waste a bunch of time wondering why it's not working. Ask a friend to try and connect to the server first before making assumptions.

That's it! I got it working this way and was able to have a number of friends join to play some games. You can proceed from here with the SuperUser account to create channels, add admins/mods, manipulate ACL's, etc. (I may cover these things more in future tutorials).

Thanks for reading! If you have any questions or want to point out something unclear/wrong, post a comment.

Wednesday, January 4, 2012

RSS feed(s) to MySQL database - a script using Simplepie and PHP in Codeigniter

A few weeks ago I was looking for a PHP script that would take RSS feeds and insert them into a MySQL database so I could manipulate them in my environment. There were a few examples here and there that were useful, but not one big example that suited my needs. Here's what I ended up doing.

First I needed to choose a RSS parser. A quick Google search revealed Magpie and Simplepie. I compared the two and ultimately chose Simplepie since it's being actively developed and the documentation seemed thorough and accessible.

After downloading the latest version (1.2.1 at the time of writing), I unzipped it and grabbed the "simplepie.inc" file. This went in the root of my /CodeIgniter/scripts folder along with a new PHP file called "rss.php".

The Code

require_once('simplepie.inc'); 

This allows the script to take advantage of Simplepie. Next:

// Create a new instance of Simplepie.
$feed = new SimplePie();


// There are two options to parse RSS feeds depending on your needs.
// The first is a single url:
$feed->set_feed_url('http://www.yoururl.com/rss.xml');
// The second is an array of feeds, if you're parsing more than one:
$feed->set_feed_url(array(
'http://www.yoururl.com/rss.xml',
'http://www.yoururl.com/rss.xml'
));

// Only use one of the above ways. Comment out or delete the other.

// Set a folder where the cache can reside.
$feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/CodeIgniter/application/cache');

// If you're on Dreamhost like I am, you'll need to modify the cache location to something like this:
$feed->set_cache_location('/home/[UserName]/myFolder/cache');
// This will ensure the output from the RSS feed matches the MySQL encoding, otherwise you end up with characters like this: â€
$feed->set_output_encoding('ISO-8859-1');
// Initialize Simplepie.
$feed->init();

// This makes sure that the content is sent to the browser as text/html and the UTF-8 character set (since we didn't change it).
$feed->handle_content_type();


Next we need to establish a database connection. For testing purposes, I ran this script on my local machine using XAMPP.

// Make sure to put in the proper server, username, and password information here.
$con = mysql_connect("localhost", "mysql_username", "mysql_password");
// Select the database you want to use.
mysql_select_db("myDB", $con);

// Then check if the connection failed. If it did, die with the error message.
if (!$con)
{ die('Could not connect: ' . mysql_error()); }

Now it's time to loop through the parsed items and load them to the database.

foreach ($feed->get_items() as $item)
{
// Here are some of the various items you can pull from an RSS feed:
        $permalink = $item->get_permalink();
$title = $item->get_title();
$content = $item->get_description();
$date = $item->get_date('Y-m-j g:i:s');

        // This next part will check for duplicated items by hashing the content and comparing it to the hashes in the database. This part is optional, but recommended.
        $content_hash = md5($content);
$result = mysql_query("SELECT * FROM my_posts WHERE content_hash = '" . $content_hash . "'");
$num_rows = mysql_num_rows($result);

if ($num_rows > 0) { }
        // If this item's hash doesn't match any in the database
else
{
// This part will check if the date has been set. Sometimes feeds don't post the date so I found this to be necessary. If it has a date, then INSERT everything, if not, set a default date in MySQL and don't INSERT the date.
                if (isset($date))
{
mysql_query("INSERT INTO my_posts (date, content, content_hash, url, title) VALUES ('" . $date . "', '" . $content . "', '" . $content_hash . "', '" . $permalink . "', '" . $title . "')");
}
else
{
mysql_query("INSERT INTO my_posts (content, content_hash, url, title) VALUES ('" . $content . "', '" . $content_hash . "', '" . $permalink . "', '" . $title . "')");
}
}
}

echo "SCRIPT COMPLETE.";

// Finally, remember to close the connection.
mysql_close($con);

That's it. I can run this, parse feeds, grab the data and INSERT it into the MySQL database. There's probably a more elegant and simple way to do it, but this worked for my needs. From here you can access these posts and manipulate them on your site however you please. I added the ability to comment, rate them, modify and delete, etc.