My Simple MySQL Class

Status
Not open for further replies.

lucab

New member
Jan 4, 2007
676
3
0
Just started teaching myself PHP in the last month or so, and I have begun to develop some very useful little tools that I use daily.

I thought I would share this class I made for MySQL. Here is the code:

PHP:
<?

######################################
###########   MySQL Class   ##########
######################################

class mysql{


  //define our variables
  var $sql, $server, $username, $password, $db, $table, $fields, $columns, $data, $purpose, $vars, $isData, $isColumns, $isFields, $match, $row, $mvalue, $matches;


  //constructor variables required when defining a new object
  function __construct($server, $username, $password){
    $this -> server = $server;
    $this -> username = $username;
    $this -> password = $password;
  }


  //check to see if we can make a connection
  function connect($db){
    $server = $this -> server;
    $username = $this -> username;
    $password = $this -> password;
    mysql_connect($server, $username, $password) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());
  }


  //create a table
  function createTable($db, $table, $fields){
    $this -> connect($db);
    $isFields = "fields";
    $fields = $this -> implodeData($fields, $isFields);
    mysql_query("CREATE TABLE $table($fields)");
  }


  //insert data into table
  function insertData($db, $table, $columns, $data){
    $isData = "data";
    $isColumn = "column";
    $this -> connect($db);
    $data = $this -> implodeData($data, $isData);
    $columns = $this -> implodeData($columns, $isColumn);
    $sql = "INSERT INTO $table ($columns) VALUES ($data)";
    mysql_query($sql) or die(mysql_error());
  }


  //delete one or more entries from a given column
  function deleteData($db, $table, $column, $match){
    $this -> connect($db);
    if (is_array($match)){
      foreach($match as $mValue){
        $mValue = "'$mValue'";
        $sql = "DELETE FROM $table WHERE $column = $mValue";
        $matches = mysql_query($sql) or die(mysql_error());
      }
    }else{
      $match = "'$match'";
      $sql = "DELETE FROM $table WHERE $column = $match";
      $matches = mysql_query($sql) or die(mysql_error());
    }
    return $row;
  }


  //create a string from an array for our sql query
  function implodeData($vars, $purpose){
    if ($purpose == "data"){
      $vars = implode("\", \"", $vars);
      $vars = "\"$vars\"";}
    else{
      $vars = implode(", ", $vars);
    }
    return $vars;
  }


  //query using select with a where operator
  function selectData($db, $table, $column, $match){
    $this -> connect($db);
    if (is_array($match)){
      foreach($match as $mValue){
        $mValue = "'$mValue'";
        $sql = "SELECT * FROM $table WHERE $column like $mValue";
        $matches = mysql_query($sql) or die(mysql_error());
        while ($row = mysql_fetch_array($matches)){
          foreach($row as $rValue){
            echo "$rValue<br />";
          }
        }
      }
    }else{
      $match = "'$match'";
      $sql = "SELECT * FROM $table WHERE $column like $match";
      $matches = mysql_query($sql) or die(mysql_error());
      while ($row = mysql_fetch_array($matches)){
        foreach($row as $rValue){
         echo "$rValue<br />";
        }
      }
    }
    return $row;
  }
  

  //here is the updating function
  function updateData($db, $table, $column, $old, $new){
    $this -> connect($db);
    $old = "'$old'";
    $new = "'$new'";
    $sql = "UPDATE $table SET $column=$new WHERE $column=$old";
    mysql_query($sql) or die(mysql_error());  
  }


} 


?>
So basically you put this code into a file called "mysql.php." Then at the top of the script where you are going to be doing DB queries, put

PHP:
require('mysql.php');
$mysql = new mysql($server, $login, $password);
The meaning of those constructor variables should be pretty self evident. Each time you create a new mysql object, you need to set some basic variables. These are defined in the __construct() function.

Then when you have to make a query, specifiy which db you want to connect to, putting

PHP:
$mysql_connect = $mysql -> connect($db);
To insert data from array $matches, for example, use

PHP:
foreach ($matches as $match){
  $mysql_insert = $mysql -> insertData($db, $table, $columns, $match);
}
I use a function within the class itself to format the data properly for SQL calls. I like to assign a variable with the returned data, to see any errors and such. If you see nothing after calling insertData, that means that it was successful. Perhaps you could add a "$match was added!\n"; or something along those lines. Also, you may want to use an instance variable if you are running a very long script to save on memory after your echo it or var_dump() it out.

I realize this will be rather basic to a lot of you, but I def think this could help out some PHP n00bs like myself. If you are using mysql a lot, this is very useful and saves a lot of time. It is similiar to the PEAR DB class, in that it makes your life a whole lot easier working with db's, although PEAR is obv a lot more robust.

Speaking of which, if any of the more experienced coders would like to jump in and point out ways which I could expand upon this script and make it more robust, please do so.

I am working on a class that expands lerchmo's bot class that solves captchas, along with one that auto follows a link in an email (verification link).

Look for these in the near future.

lucab
 


I don't really use OOP much, because I think it's only useful for some really complex problems, and a lot of PHP developers get to enthralled with it to realize that. Then they end up using it as complete overkill to solve a problem with OOP that could easily be done with procedural code.

In this case, it's definitely a good thing to be writing this for practice. But functionally, I don't really see the point, sorry. It basically just provides a way to write MySQL queries differently. It's still the same amount of work for you. The point of a class should be to simplify things for you - this just complicates it even more.

I don't really use MySQL classes, as I have said, but from what I have seen, this class could benefit from not being just MySQL. Build in support for other databases. Also, you could make classes to extend it that really serve a purpose in holding a bunch of methods that you perform on a page-to-page basis on specific sites. For instance, if you have to update a session in the DB all the time, make a method for that.

Hope that wasn't too hard to follow. I'm not a big fan of OOP like I said, so I could be a bit biased. :P
 
lol @ "I'm not a big fan of OOP" - what sort of development do you do? To address your point about expanding this to include other db's, well that is what PEAR is for and is very versatile and well documented.

As far as making things more complicated, are you out of your mind? Without using a method like this I would have to connect to mysql, tell it which db to connect to, and then implode an array so it is properly formatted for a sql query. Not to mention all the die(mysql_error()) and SQL queries which I otherwise I find myself typing over and over again (the same thing).

So please let me know how this doesn't save time, maybe I am just wasting time building these tools which I thought were going to simplify my life. Hmm...

edit : maybe i misunderstood your post and you would suggest just using a function to do this? that would be fine too, it would do pretty much the same thing. the reason why i like creating the object is because with one script running, we are going to be using the same login info and we can do each needed step with only one line of code from there
 
Speaking of PEAR why not just use the pear modules or PDO?

This does make things more complex. First off you don't have proper error handling, secondly you don't really cut out that much code.

You aren't wasting your time because they are good learning projects. But reinventing the wheel with less functionality isn't the way to go.

As for the other posters comments about OOP development. I come from a C background and hated OOP for a very long time till I got into it, not I use it for everything(It helps that my coding is now 50/50 php5 and ruby). It has it's place....everywhere. Procedural development is ok for most things but once your scripts start getting larger oop is the way to go.
 
If you're ever planning to come back and rework or reuse anthing other than a very trival piece of code, then OOP will usually (usually...) help a great deal. For throwaway scripts that you just want to make work this once, then OOP is largely superfluous.

But yeah, Pear does this kind of thing quite nicely.
 
Eh, not a fan of this abstraction..

I just use a few wrapper functions around the built in mysql_* functions..

query_fetch_first($sql, $column=false);
query_fetch_all($sql);
query_fetch_result($sql);
query($sql);

etc

It's not like anyone needs DB abstraction anyway (for our purposes, it's MySQL all the time).
 
Thx for the feedback. This was more of an academic project, and as some said, yes, this is good practice obv. Perhaps it is a little overboard.

This made me rethink my plan to make a captcha class, considering the different regex needed to scrape token / image url and such it is getting to be a little bogged down. It might still be the most efficient way of doing things.

It seems that some things are better left to simple function calls as opposed to going the OOP route, because I am trying to make my life easier, not more difficult.
 
If you're looking to build a DB abstraction class, I'd look into building a layer on top of PEAR/PDO. I went with PDO because my host had a tendency to recompile things on the shared host every once in awhile and would neglect to add the PEAR modules they had. PDO should be compiled in.

For most of my projects requiring a DB backend, I use a base db class to handle the connections, and then have each table extend that base class for their specific traits. As a quick example:

PHP:
class db {

	protected static $dbh = false;
	
	protected function connect(){
		try {
			self::$dbh = new PDO(CONN_STRING, USER, PASS);	// these are defined in config.php
			// set uppercase, error mode = exceptions
			self::$dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);
			self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		}
		catch (PDOException $e) {
   			// log the error
   			self::log_error($e);
   		}
	}
        // other base helper classes - log function, etc.
}

Then each of my tables will extend this class
PHP:
class table extends db{
    public function insert($array)
    {
    	try{
    		if(!self::$dbh)
    			$this->connect();
    		$ins = self::$dbh->prepare("INSERT INTO table " .
    				"(id, col1, col2, col3 ) " .
    				"VALUES " .
    				"(null, :col1, :col2, :col3)");
    		$params = array(':col1' => $array['col1'],
    						':col2' => $array['col2'],
    						':col3' => $array['col3']
    						);

    		$res = $ins->execute($params);
    	}
    	catch (PDOException $e) {
   			// log the error
   			self::log_error($e);
   		}
   		return $res;
    }
    // add more functions to load a record, modify, etc.
}

The thing I really like about this approach is I feel it's very clean in its approach - when I need the data, I have very simple calls to these classes. As you can probably guess, I am a proponent of OOP and also to a lesser extent a MVC approach.

Assuming you follow consistent naming conventions, you can also write another script file that will automatically generate your model classes for you too. So even if you have 50 tables for a particular site, you'll have an easy access layer for all of them after running a single script.
 
lol @ "I'm not a big fan of OOP" - what sort of development do you do? To address your point about expanding this to include other db's, well that is what PEAR is for and is very versatile and well documented.

As far as making things more complicated, are you out of your mind? Without using a method like this I would have to connect to mysql, tell it which db to connect to, and then implode an array so it is properly formatted for a sql query. Not to mention all the die(mysql_error()) and SQL queries which I otherwise I find myself typing over and over again (the same thing).

So please let me know how this doesn't save time, maybe I am just wasting time building these tools which I thought were going to simplify my life. Hmm...

edit : maybe i misunderstood your post and you would suggest just using a function to do this? that would be fine too, it would do pretty much the same thing. the reason why i like creating the object is because with one script running, we are going to be using the same login info and we can do each needed step with only one line of code from there

lol @ "I'm not a big fan of OOP" - what sort of development do you do?

Are you serious? PHP isn't even an object oriented language. OOP has only been around since PHP5, and I learned PHP without that. I didn't say I don't code in OOP, I use it when I think it's necessary and makes my life easier. As a matter of fact, I was writing a class just today, but it actually has a purpose and will save me a lot of extra coding.

What I mean is that I don't see the difference between this:

Code:
require('mysql.php');
$mysql = new mysql($server, $login, $password);
$mysql_connect = $mysql -> connect($db);
and this:

Code:
mysql_connect($server, $login, $password);
$mysql_select_db($db);
That's what I mean when I'm saying it isn't saving you any work. Also, this is really no different than a simple insert query:

Code:
foreach ($matches as $match){
 $mysql_insert = $mysql -> insertData($db, $table, $columns, $match);
And don't play your OOP-is-God-and-if-you-don't-use-it-you-can't-code card, because that's not what I'm arguing. I'm saying that this particular class of yours really isn't saving any work. If you show me a solid example of where it can, then I may think more of it. But it isn't anything special. It's good practice for you learning PHP, but that is about it.
 
Are you serious? PHP isn't even an object oriented language. OOP has only been around since PHP5, and I learned PHP without that.

Correction, you were able to use OOP (although not complete) in PHP4.

OOP gives me headaches. I still use it sometimes though... :-)
 
Hmmm, idk. Whatever the case, time saving or not, it is helping me in terms of learning a TON and I am already starting to develop a solid base for PHP and Ruby within a very short period of time. The main focus of writing this script was to get better at scripting and being creative at times to problem solve.

Since Perl 5 and PHP 4 they have been implementing OOP aspects, and PHP 5 has even more robust OOP features. There are some great classes out there - e.g., snoopy seemed pretty cool. Personally I am just using a custom version of lerchmo's bot class, which saves a TON of time eliminating redundant curl initializing.

I would be very interested to hear some other perspectives on this. Specifically how it relates to building tools that would be very helpful for AM and SEO. I guess I will hijack my own thread a little bit.

For instance, I am working on a script that creates accounts at over 100+ (at the moment) social web 2.0 sites and setups a profile page and whatever else. These accounts are going to be kept "active" to a degree. Now for something this involved, I am not sure as to the best way to set something like this up from a coding / structural POV. Obv efficiency is a big deciding factor, right there with reliability and usability.

If there is interest in this subject, I can start another thread.
 
i was going to start a PHP thread in the future and walk through noobs step by step. I am learning it currently, but i just don't have time. I work all day and work out and relax at night. I need to figure out how i can get more time to learn. Are you working right now? How did you learn all this in under a months time??

ps. Programming comes easy to me
 
Personally I am just using a custom version of lerchmo's bot class, which saves a TON of time eliminating redundant curl initializing.

I use that, too. It helps to no end. In fact it was probably more valuable to me than the actual software lerch wrote. :D
 
Just started teaching myself PHP in the last month or so, and I have begun to develop some very useful little tools that I use daily.


You should go with this: ADOdb Database Abstraction Library for PHP (and Python) for MySQL, PostgreSQL, Microsoft SQL Server, Oracle, Firebird, Interbase, LDAP, Access, VFP, DB2 and many other databases

Really good stuff. It's good to learn the stuff yourself as it helps in the longrun. But there is a certain point where it won't be worth your time to re-invent the wheel.
 
I'd recommend learning the ActiveRecord methodology if you're looking at a database abstraction layer. Rails uses ActiveRecord, as does it's php counterpart Cake. If you don't want to get into an entire framework like cake, the link grant29 provided above has an ActiveRecord implementation you can read about at:

ADOdb Active Record
 
If you're going to code procedurally and not use design patterns I'd suggest sticking with procedural. However if you plan on build very large system with a lot of moving parts the more you code it re-usable the better. OOP allows a lot more decoupling then procedural. But again if you just going to make a Yahoo Answers spam tool or a site generator then OOP is just not necessary.
 
I try to use OOP whenever possible. PHP5 still has a fucked OO model and I generally don't LIKE using OO concepts in PHP.

With that said, this class could stand to be improved. I like having my database username, password and host information stored as constants in a main configuration file. My own MySQL class looks more like this.

Code:
$conn = new MySQL();
$sql = "SELECT * FROM `some_table`";

$rs = $conn->query($sql);

I never like the arguments for when OOP is or is not necessary. One of the major benefits of OOP is that you can write something in such a way that it can be used or abstracted later for something different.

If you do any reasonable amount of programming you will always find that the little project you wrote procedurally turned out to be a bit larger and more complex that you had expected and now a few months later you want to adapt that idea into something bigger and better but you can't because your original code was sloppy and hacked together and you can't figure out what the hell you were doing at the time.

Most PHP people are just plain afraid of OOP because they don't know what they're doing and they figure "Well what I'm doing now seems to be working, why change?" and they never bother learning OOP principles.
 
hmm lots of interesting points of view in this thread. have been really sick, haven't had a chance to respond.

To answer sp111's question about how I lgot this far in a month, well I started by going through the PHP and MySQL tutorial over at tizag.com. I think that might be a WF member's site, not sure though. I just started working on some basic scrapers using file_get_contents and learning some regex. Then I started learning some curl. Smaxor's oooff.com is cool too for a very cursory outline of PHP and curl.

I bought some O'Reilly books - Programming PHP, Mastering Regular Expressions, Ajax on Rails, and I had a few others. Then I just started reading and scripting as I read, I find learning by doing to be the quickest way.

To date I have made a slew of different scraper programs, a couple simple gb spammers, a couple simple forum spammers, an auto RSS feed creator, an auto pinger that pings out a list of sites at different ping sites, a console for mining longtails via free tools, some dynamic content generation for my drupal sites, fucked with the Drupal API a little bit, an email autoresponder, and email link follower (for confirmation email) and some other shit.

Right now I am working on a tool that auto registers and posts to over 100 different social sites (bookmarking, blog, network, answers, etc...). This tool is probably something a lot of people have already developed, but I am learning a ton as I go along. For example, the best way to setup a system that really has to use OOP to be efficient. I am studying about abstract classes and interfaces right now, considering I have to build a strong foundation for each platform (blog, bookmark, etc...).

The main thing is just to dive in and start DOING. I can't stress this enough. You can sit there and read every programming book under the sun, but when it comes time to write some code, you are going to flounder if you don't have experience. Get some goals, get some knowledge, and then just go balls to the wall trying to get to the finish line. Yes, you will encounter many problems along the way, but taking the time to solve each one of these problems will give you the skills and experience needed to succeed on the coding side of IM.

Happy Coding,

lucab :D:D:D:D:D:D:D
 
Wow, this code is useless, never heard of Propel? Why the fuck is Tobsn banned when he was posting code which was actually USEFUL?!?!
 
Status
Not open for further replies.