well, if you don't know how to code it procedurally, you'll have a hard time using OOP.
**These are basic examples and are UNTESTED**
for example, using procedural coding:
PHP Code:
<?php
// connect to mysql
mysql_connect("server", "user", "pass") or die(mysql_error());
echo 'Connected to MySQL.';
// select database
mysql_select_db("db_name") or die(mysql_error());
echo "Connected to Database";
// query
$SQL = ''; // put your SQL query here
$result = mysql_query($SQL);
while($row = mysql_fetch_array($result)){
// do stuff with results
}
Object-oriented example:
PHP Code:
class DB{
// declare class variables
private $server;
private $user;
private $pass;
private $dbname;
private $dbhandle;
// this function builds the $DB object
// call: $DB = new DB('server', 'user', 'pass', 'dbname');
function __construct($server, $user, $pass, $dbname){
// assign the values you're using to the class variables
$this->server = $server;
&this->user = $user;
$this->pass = $pass;
$this->dbname = $dbname;
// try to connect
$this->connect();
}
// this function makes the mysql connection
function connect(){
try{
// assign mysql connection to class variable; if successful
if($this->dbhandle = mysql_connect($this->server, $this->user, $this->pass)){
// try to select DB
if(mysql_select_db($this->dbname)){
return TRUE;
}else{
// this is the error if mysql_select_db() fails
throw new Exception(mysql_error());
}
}else{
// this is the error if mysql_connect() fails
throw new Exception(mysql_error());
}
}catch(Exception $e){
// show any errors
echo 'MySQL error: '.$e->getMessage();
return FALSE;
}
}
// this function performs a query
// call: $DB->query("SQL statement");
function query($SQL){
// check if the db handle is working and try to reconnect if not
if(!$this->dbhandle){ $this->connect(); }
// perform query
try{
if($result = mysql_query($SQL)){
return $result;
// optionally, you could call another function to process results
// e.g., something like "$this->printresults();"
}else{
throw new Exception(mysql_error());
}
}catch(Exception $e){
echo 'Error in query; '.$e->getMessage();
return FALSE;
}
}
}
as you can see, OO is a lot more overhead. it's useful if you're going to be doing the same thing over and over: a class is basically a collection of related functions and results that you can use. if you're learning, or only doing a few queries, do it procedurally.
Bookmarks