Blog Navigation
Partners
Latest Activity
Phil explains how to use the old telephone tones to wane off telemarketers!
Posted on: January 22nd, 2012 by Famous Phil
Its now time to become serious with my blog again after such a long lapse in real content.
When building new applications, it always seems like I start with the grand picture requiring no massive data storage and shortly after I begin, I find myself needing a database connection. I’ve made the mistake several times now of not starting with a dedicated database class that connects to MySQL, and I always find myself googling for pre-made classes that don’t do exactly what I need, so I’ve decided to post my own for future reference. As a result, I’m going to make sure that when I Google, I find my own reference before someone else’s
Hopefully this is useful to someone else.
PHP’s MySQL singleton class:
<?php
// Copyright (c) 2012 Philip Matuskiewicz www.famousphil.com
// To use:
// require_once("Mysql.php");
// $db = new Mysql();
class Mysql{
private $server = "localhost";
private $username = "";
private $password = "";
private $database_table = "";
private static $instance;
private function __construct(){
$this->connect();
}
public function connect(){
mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->database_table);
$this->q("set names 'utf8'");
}
//query the database
public function q($query){
$r = mysql_query($query);
return $r;
}
//returns an array containing all the rows that were returned
public function qr($query){
$r = $this->q($query);
if (mysql_num_rows($r) > 0) {
$res = array();
while ($arr = mysql_fetch_array($r)) {
array_push($res, $arr);
}
return $res;
} else {
return null;
}
}
//number of rows returned
public function nr($query){
return mysql_num_rows($this->q($query));
}
//last inserted row id is returned
public function lid(){
return mysql_insert_id();
}
//close the database connection
public function c(){
mysql_close();
}
public static function singleton(){
if (!isset(self::$instance)) {
$c = __class__;
self::$instance = new $c;
}
return self::$instance;
}
public function __clone(){
trigger_error('no clone', E_USER_ERROR);
}
}
?>
The Python MySQL singleton implementation is similar, but includes an external file named config.py in this example
--> config.py (configuration information for the MySQL class)
dbhost = "localhost";
dblogin = "";
dbpassword = "";
dbname = "";
--> MySQL.py (The MySQL class)
#!/usr/bin/env python
# Copyright (c) 2012 Philip Matuskiewicz www.famousphil.com
#to include / use, insert the following lines in the code
#import imp;
#mysql = imp.load_source("MySQLConnector", "PATH_TO_PYTHON_FILE/mysql.py").MySQLConnector();
#result = mysql.tryquery("Mysql Query Here");
import sys;
import os;
import string;
import base64;
import MySQLdb;#mysql library (you will need to install this on the system)
#MySQL Singleton Class
class MySQLConnector(object):
_connection = None;
_instance = None;
def __init__(self):
try:
if MySQLConnector._instance == None:
MySQLConnector._instance = self;
MySQLConnector._instance.connect();
except Exception, e:
print "MySQL Error "+str(e);
def instance(self):
return MySQLConnector._instance;
def get_connection(self):
return MySQLConnector._connection;
def connect(self, debug=False):
try:
for line in open('includes/config.py'):
#this can be dangerous, but sources / executes lines in config.py, which contains the db info
#alternatively, you can just set the variables here manually
exec('%s = %s' % tuple(line.split('=', 1)));
MySQLConnector._connection = MySQLdb.connect(dbhost, dblogin, dbpassword, dbname);
if debug:
print "INFO: Database connection successfully established";
except Exception, e:
print "ERROR: MySQL Connection Couldn't be created... Fatal Error! "+str(e);
sys.exit();
def disconnect(self):
try:
MySQLConnector._connection.close();
except:
pass;#connection not open
#returns escaped data for insertion into mysql
def esc(self, esc):
return MySQLdb.escape_string(str(esc));
#query with no result returned
def query(self, sql):
cur = MySQLConnector._connection.cursor();
return cur.execute(sql);
def tryquery(self, sql):
try:
cur = MySQLConnector._connection.cursor();
return cur.execute(sql);
except:
return False;
#inserts and returns the inserted row id (last row id in PHP version)
def insert(self, sql):
cur = MySQLConnector._connection.cursor();
cur.execute(sql);
return self._connection.insert_id();
def tryinsert(self, sql):
try:
cur = MySQLConnector._connection.cursor();
cur.execute(sql);
return self._connection.insert_id();
except:
return -1;
#returns the first item of data
def queryrow(self, sql):
cur = MySQLConnector._connection.cursor();
cur.execute(sql);
return cur.fetchone();
#returns a list of data (array)
def queryrows(self, sql):
cur = MySQLConnector._connection.cursor();
cur.execute(sql);
return cur.fetchmany();
#end class MySQLConnector
Tags: mysql, php, Python, Singleton, Source Code
Posted in Programming, Technology
|| 2 Comments »
Posted on: March 30th, 2011 by Famous Phil
This is a video blog continuation of week 2 (see the previous post).
Background: I was asked by the IEEE student club at UB (http://wings.buffalo.edu/sa/ieee) to redo my lecture series on developing websites. I know that my website isn’t the best visually designed website in the world (and I’m actively looking for talent that can help me fix this in exchange for my programming skills), but I do know a lot about how to code websites well. Anyways, here are the videos from Lecture 3. There will be a fourth and final lecture next week. As always, thanks for reading!
Part 1:
Part 2:
Part 3:
Part 4:
Tags: .htaccess, adobe, club, cms, content management system, educational, educational web developmhtml, Google, hosting, html, ieee, ieee student club, mysql, php, phpdesigner, putty, rewrite, security, student, university at buffalo, vim, web development, website, wordpress
Posted in Hosting / Server Administration, My Site, Programming, Student Life, Technology
|| No Comments »
Posted on: March 23rd, 2011 by Famous Phil
This is a video blog continuation of week 1 (see the previous post).
Background: I was asked by the IEEE student club at UB (http://wings.buffalo.edu/sa/ieee) to redo my lecture series on developing websites. I know that my website isn’t the best visually designed website in the world (and I’m actively looking for talent that can help me fix this in exchange for my programming skills), but I do know a lot about how to code websites well. Anyways, here are the videos from Lecture 2. As always, thanks for reading!
Part 1:
Part 2:
Part 3:
Part 4:
Part 5:
Tags: adobe, educational, Google, hosting, html, ieee student club, mysql, photoshop, php, putty, university at buffalo, vim, web development, website
Posted in Hosting / Server Administration, My Site, Programming, Student Life, Technology
|| No Comments »
Posted on: March 10th, 2011 by Famous Phil
It seems like its been a while since I last posted to my blog. As usual, the mid semester grind is hitting my time hard, so I don’t have the resources to write here as often. Thankfully this is my last semester as a Masters student, *yay*. So coming up soon, I will be writing a blog on regular expressions, I’m still in the process of making it, so it might take a while. I’ve also got a great blog for April fools day, so stay tuned for that!
Now onto the topic of this blog. This is a video blog (go figure, right?). Actually, I was asked by the IEEE student club at UB (http://wings.buffalo.edu/sa/ieee) to redo my lecture series on developing websites. I know that my website isn’t the best visually designed website in the world (and I’m actively looking for talent that can help me fix this in exchange for my programming skills), but I do know a lot about how to code websites well.
Being the kind of person who likes to share knowledge, I agreed to give the lecture series with updated information. John suggested that I video tape the lectures and post them to my blog, which I thought was a great suggestion. So in the next 5 to 6 weeks, I will be posting youtube 720p HD recordings of the lecture series to here. Feel free to watch it and make comments about my presentation skills. I know that I’m not perfect, so I’m always open to suggestions!
As always, thanks for reading!
Part 1:
Part 2:
Part 3:
Tags: adobe, development, education, Google, hosting, html, ieee, mysql, php, putty, student club, university at buffalo, vim, Web, website
Posted in Hosting / Server Administration, My Site, Programming, Student Life, Technology
|| No Comments »
Posted on: August 2nd, 2010 by Famous Phil
This topic plagues me to death every time I need to do some administrative function MySQL simply because I don’t do it every day. I have 3 servers that I manage entirely via the command line now and all 3 require me to know at least some MySQL. Unfortunately, I always end up going to several sources to get all the information I need. So instead of doing that in the future, I’m writing this blog as a centralized reference for everything I need. Hopefully you can use this blog as much as I will!
Note: You will need to click the “show code” icon in the top right corner to view the code entirely for some of the blocks that are longer than the code box.
POST UPDATED 6/5/2011 (deleting a user / listing users)
Tags: administration, cheat, command line, interpreter, mysql
Posted in Hosting / Server Administration, Programming
|| 4 Comments »
Posted on: March 11th, 2010 by Famous Phil
Today, I will pursue a topic that all of us wish wasn’t necessary to discuss, but it is a fact of life. Backups are required in life and this isn’t a new concept, but poor backups can be devastating when you find out that it doesn’t work (and that is usually when you need it the most). I’ve spent a lot of time making changes to my backup systems over the years, but they are never perfect and I constantly find new flaws that I constantly work to fix.
A few weeks ago, I found a major flaw in my backup system that I never really thought about in the past. My backups would run every night by essentially pushing the latest backup to another server that I run. This server had an account on it where the backup would neatly upload then not be touched again until the next backup cycle ran. To access the backup, all I had to do is login as root on my production system (the system that runs famousphil), then request the backup. Passwords are entirely controlled through keys, so I didn’t have to do anything special or know anything to gain access to my backup server. Unfortunately, if all I needed was my root password / key to do that, if a hacker got into my system, they essentially could completely destroy my backup system as well.
With the ever growing threat of hackers attempting to compromise my network of servers, I’ve began giving more thought to hack attempts and prevention along with hard disk and other physical server failures (which also happen). Because of these thoughts, I’ve implemented a new backup routine that fixes most of my issues with a hacker gaining access to my network. If I discover a hacker has penetrated one of my servers within 12 hours, I will always be able to restore a backup that is no more than 3 days old now. The same goes for a hard disk failure / natural disaster. I do not feel it is in the best interest of Matthouse to disclose the new backup system and exact scheduled times, but I thought that it would be appropriate to share a little insight into that thought that I’m sure many other system administrators might fall into at one point or another.
Another threat that I found with my backup system was that part of my backups were incomplete. For any admin that thinks backing up /var/lib/mysql is appropriate to backup MySQL, think again. About 2 months ago, I thought this was appropriate, so I began backing up MySQL this way (I never really thought to check it initially since the server was brand new). I normally check the redundancy of my backups about once every 2-3 months. During my redundancy check, I always check everything and I discovered that I could not restore the MySQL database server from that directory easily. Since I have the original server still running, I came up with a new backup procedure that works much better and can actually be restored.
For all of you who need to backup an entire MySQL server, here are the 2 commands that will help:
Those are the 2 major points I wanted to make in this post. In conclusion, I recommend that you make a backup schedule for your servers and verify that loop holes don’t exist in it. I’m constantly looking for loop holes and I patch them as I find them. Also, verify your backups! I would have never realized that MySQL wasn’t being backed up unless it was for verifying that my backups are in tact and can be restored. I verify my backups every other month and I recommend that every system admin does so.
For anyone at home, HARD DRIVES DO FAIL. I strongly recommend keeping any data that you could not afford losing on a flash drive or external hard drive where if your computer did fail, you would still have your data. Unfortunately, data is unrecoverable at cheap rates, making a backup is a cheap insurance policy to avoid complete disaster!
Tags: backup, hacker, hard drive failure, mysql
Posted in Hosting / Server Administration
|| 2 Comments »
Posted on: April 28th, 2009 by Famous Phil
A good place to introduce this topic is by stating that I consider myself a “good” system administrator. I consider myself above average when it comes to Windows Server administration, and “average” when it comes to Linux server administration. Normally, regardless of platform (Linux or Windows), I usually know enough not to get myself into trouble, yet rectify the problem that is presented to me.
Prior to last October (2008), I have solved a wide array of problems consisting of Apache malfunctions and complete Server Hard Drive failures requiring data recovery, to simply having to unblock a person’s ip address from the firewall because they tried to login to the server incorrectly too many times. I never really messed a server up so badly that I couldn’t undo what I attempted to fix in the first place.
Tags: administration, blunder, delete, disk space, hosting, Linux, mysql, var, var/lib/mysql, windows
Posted in Hosting / Server Administration, Personal
|| 2 Comments »