I work on a web application that I inherited from a colleague long gone. To connect to the MySQL database I use the following classes:
statement.php
<?php
//class sql
//{
class Statement
{
private $m_connection;
function __construct($connection)
{
$this->m_connection = $connection;
}
function query($query)
{
$connection = $this->m_connection;
$handle = $connection->getHandle();
$result = mysql_query($query,$handle);
if ($result === FALSE)
throw new Exception(mysql_error());
$instance = new Result($this);
$instance->setHandle($result);
return $instance;
}
}
//}
?>
result.php
<?php
//class sql
//{
class Result
{
private $m_handle;
private $m_statement;
function __construct($statement)
{
$this->m_statement = $statement;
}
function setHandle($handle)
{
$this->m_handle = $handle;
}
function fetch()
{
$handle = $this->m_handle;
$row = mysql_fetch_array($handle);
return $row;
}
}
//}
?>
connection.php
<?php
include_once("statement.php");
include_once("result.php");
//class sql
//{
class Connection
{
private $m_handle;
function __construct($server,$username,$password)
{
$handle = mysql_connect($server,$username,$password);
$this->m_handle = $handle;
}
function __destruct()
{
$handle = $this->m_handle;
@mysql_close($handle);
}
function createStatement()
{
return new Statement($this);
}
function getHandle()
{
return $this->m_handle;
}
}
//}
?>
and named.php
<?php
include_once("connection.php");
function createNamedConnection($name)
{
if ($name == "dbalias1")
{
$connection = new Connection("first.host.com","user","uspw");
$statement = $connection->createStatement();
$statement->query("USE db1");
return $connection;
}
if ($name == "dbalias2")
{
$connection = new Connection("second.host.com","user2","nouse");
$statement = $connection->createStatement();
$statement->query("USE db2");
return $connection;
}
return null;
}
?>
To have a connection I can use the following script:
$connection = createNamedConnection("dbalias1");
$statement = $connection->createStatement();
$query = "SELECT *
FROM tContent c
WHERE c.cID > 100";
$result = $statement->query($query);
while(($row = $result->fetch()) !== FALSE){
//do something
}
The problem is that those classes caused me a lot of trouble, and I'm sure there is work to be done on them, but I don't know where to begin, to make those classes more secure and easy to use.
Warning: mysql_query(): 7 is not a valid MySQL-Link resource in E:\webroot\dbtest\lib\statement.php on line 18
and it is difficult each time to find out the reason why. But it is only one example of the problem I had. To summarize debugging is quite difficult. – Eldros Feb 4 '11 at 14:12__autoload()
function. :) – Jeffrey Feb 4 '11 at 15:23