Jump to content

[SOLVED] learning OOP..please advice


DanDaBeginner

Recommended Posts

:) Hi people. im so trying to grasp the OOP approach. heres my code so far with basic mysql connection.. i need to know if im making sense when it comes to OOP approach? please need some advise..

so far heres my class code..hope it make sense..am I?  besides the error handling, what else can you advice? I know I can make the error handling more inteliigently.. am I tooo far from OOP?

<?php
class sql {
private $root;
private $un;
private $pass;
private $dbname;
private $conn;
private $query;

function __construct($root,$un,$pass,$dbname) {
	$this->root = $root;
	$this->un = $un;
	$this->pass = $pass;
	$this->dbname = $dbname;
}

function sqlConnect() {
	$conn = @mysql_connect($this->root,$this->un,$this->pass);
	if ($conn) {
		$this->conn = $conn;
	} else {
		echo 'Connection ERROR!';
	}
}

function sqlSelectDB() {
	$db = @mysql_select_db($this->dbname,$this->conn);
	if ($db) {
		return $db;
	} else {
		echo 'Connection ERROR in DATABASE!';
	}

}

function sqlQuery($query) {
	$runQuery = @mysql_query($query);
	if ($runQuery) {
		$this->query = $runQuery;
	} else {
		echo 'ERROR with query!';
	}

}

function fetch($assoc=FALSE) {
	if ($assoc) {
		$row = @mysql_fetch_assoc($this->query);
	} else {
		$row = @mysql_fetch_array($this->query);
	}
	return $row;
}
}
?>

 

and heres the example coding if im going to use this class

<?php
require_once('connect.class.php');

$new_sql = new sql('localhost','root','','testing');
$new_sql->sqlConnect();
$new_sql->sqlSelectDB();
$new_sql->sqlQuery("SELECT * FROM message");
while($row = $new_sql->fetch()) {
echo '<p>'.$row[0].'<br>FROM: '.$row[1].'<br>TO: '.$row[2].'<br>Message: '.$row[3].'<br>TimeSent: '.$row[4].'</p>';
}
?>

Link to comment
Share on other sites

I would advise learning to use your scope declarations on your functions as a habit, too. Any functions you have that don't need to be accessible outside of your class (often those that directly modify your private variables) should be marked as private or protected as well. Also, if you ever think you will extend the class with child classes, use "protected" instead of "private" to allow those child classes access to the variables and functions within the parent class as well.

 

In addition to Daniel0's comment, I would recommend you go a step further. If you are using your "private" and "public" declarations, you must be using PHP5+, so I recommend you get into the habit of throwing errors from your classes where you can simply use a try-catch block to run things through. For instance, I would rewrite your structure slightly to allow the creation of the database class to connect and select the DB all at once. Also, this will let you do several things from one constructor call:

<?php
class sql {
protected $root;
protected $un;
protected $pass;
protected $dbname;
protected $conn;
protected $query;
protected $Debug;

public function __construct($root,$un,$pass,$dbname) {
	$this->root   = $root;
	$this->un     = $un;
	$this->pass   = $pass;
	$this->dbname = $dbname;

	$this->sqlConnect();
	$this->sqlSelectDB();
}

public function setDebug($var = true) {
	$this->Debug = $var;
}

protected function sqlConnect() {
	$conn = @mysql_connect($this->root,$this->un,$this->pass);
	if (!$conn) {
		$msg = "Could not connect to SQL server";
		if ($this->Debug) $msg .= "<br />\n" . mysql_error();
		throw new Exception($msg);
	}

	$this->conn = $conn;
}

protected function sqlSelectDB() {
	if (!@mysql_select_db($this->dbname,$this->conn)) {
		$msg = "Could not connect to database";
		if ($this->Debug) $msg .= "<br />\n" . mysql_error();
		throw new Exception($msg);
	}
}
}
?>

 

As you can see, the connect and select_db functions are both being called as part of the constructor. Also, I've added a "setDebug()" function that will tack on the mysql_error() message to the end of any Exceptions that are thrown when errors are encountered. Now, all you have to do is something like this:

<?php
try {
  $new_sql = new sql('localhost','root','','testing');
  $new_sql->setDebug(true); // Output more verbose error messages
} catch (Exception $e) {
  $error = $e->getMessage();
}

if (isset($error)) echo "<p class='error'>$error</p>\n";
?>

 

Just a little more streamlined, but you definitely are getting the idea. When you have something like the Debug I've outlined, though, be sure to always set debug to FALSE for production environments.

 

Good luck!

Link to comment
Share on other sites

The sucky thing about those scopes is that they are only for PHP 5 and up. My server, and generally most servers that are shared run PHP 4. I am SOL on this until my server decides to update the PHP to PHP 5, which I do not see happening for a while.

 

That try and catch would be very very nice, too bad it is PHP 5 also =\ I really need to contact my server about that =)

 

 

Link to comment
Share on other sites

The sucky thing about those scopes is that they are only for PHP 5 and up. My server, and generally most servers that are shared run PHP 4. I am SOL on this until my server decides to update the PHP to PHP 5, which I do not see happening for a while.

 

That try and catch would be very very nice, too bad it is PHP 5 also =\ I really need to contact my server about that =)

 

Correct that it is PHP5 only. That's why I recommended it. Based on the "private" declarations in the OP, he has to be running PHP5 for that to work since those declarations are also features of OOP added in PHP5+.

Link to comment
Share on other sites

Something that would be nice for yourself to do is to make functions called update and insert that will take the name of the table and an array of the data. So you could do something like this:

$db->update("articles", array("title"=>"New title", "last_view"=>time()), "WHERE id='5'"): // Syntax: update(str $table, array $data[, str $extra]);

Link to comment
Share on other sites

Something that would be nice for yourself to do is to make functions called update and insert that will take the name of the table and an array of the data. So you could do something like this:

$db->update("articles", array("title"=>"New title", "last_view"=>time()), "WHERE id='5'"): // Syntax: update(str $table, array $data[, str $extra]);

 

That would be pimp, thats a nice idea...now why didn't I think of that? =)

Link to comment
Share on other sites

Another simple, yet useful, function would be a combination of the fetch and query function. I don't know how to explain it, so I'll give you the code:

<?php
// inside the class:
function fetch_result($query, $assoc=false)
{
$this->sqlQuery($query);

return $this->fetch($assoc);
}
?>

 

In addition to sql::sqlQuery() setting the last result in a variable, make it return it as well. (Then let sql::fetch() take it as well, and if not supplied then take the last result)

 

Edit: Oh, and you should make fetching to an associative array default instead, as that is probably what you'd be using most times.

Link to comment
Share on other sites

Excellent, excellent suggestions, Daniel0! There are so many things that you can do with custom DB classes to make your life simpler. One of the things I've done is in a config file, preload all your table names with pseudonyms in a definition array, and then just do all your SQL statements using the pseudonyms. This way, when you run your query, you can do a str_replace() and get all the actual table names pasted in place. How is that useful? Well, if you're looking to install your app on numerous servers, it's not a bad idea to let your client choose a table prefix for your install (in case it's being installed in the same DB as another app). This way, your table names only have to be update in one page of the code, and the class does all the rest of the work.

Link to comment
Share on other sites

Obsidian, can you post that code? What I am wondering is how you setup the pseudonyms to be replaced, something like this?

 

$pseudoArr = array("%USERS%", "%TEMP%");
$tableArr = array("tbl_users", "tbl_template");
// then in the function after the $sql is passed you do this?

$sql = str_replace($pseudoArr, $tableArr, $sql);

// then do query running below

 

I always wanted to do it but I could never think of an efficient way to set that up or make it easier than what I was previously doing.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.