<?php
/*
* Copyright (C) 2011 Dag Jonny Nedrelid
*
* A PHP class that handles MYSQL and MSSQL database connections.
*
* The public methods open() and query() will exit the PHP script
* with error messages if a connection cannot be established and/or
* if a query returns false. query() will return an associative row
* array if a resultset with content was returned, NULL if it's
* empty. For other successful SQL statements like INSERT, UPDATE,
* DELETE, DROP, etc, query() will return TRUE.
*
* Example of usage:
include 'djDBI.php';
$db = new djDBI();
$db->open('localhost', 'database', 'user', 'pass', 'MYSQL');
$result = $db->query("SELECT * FROM testdata");
$db->close();
unset($db);
if (!is_null($result))
// Returned an associative array you can loop through.
*/
class djDBI
{
private $link, $type;
public function open($host, $database, $user, $pass, $type)
{
$this->type = $type;
switch ($type) {
case 'MYSQL':
if (!($this->link = mysql_connect($host, $user, $pass)))
$this->error('open(): mysql_connect()');
if (!mysql_select_db($database, $this->link))
$this->error('open(): mysql_select_db()');
mysql_set_charset('utf8', $this->link);
break;
case 'MSSQL':
if (!($this->link = mssql_connect($host, $user, $pass)))
$this->error('open(): mssql_connect()');
if (!mssql_select_db($database, $this->link))
$this->error('open(): mssql_select_db()');
break;
default:
$this->error('open(): Invalid type parameter.');
}
}
public function close()
{
if (is_resource($this->link)) {
switch ($this->type) {
case 'MYSQL':
mysql_close($this->link);
break;
case 'MSSQL':
mssql_close($this->link);
break;
}
}
}
public function query($s)
{
switch ($this->type) {
case 'MYSQL':
if (!($result = mysql_query($s, $this->link)))
$this->error('mysql_query()');
//$this->error('mysql_query(): ('.
// mysql_errno($this->link) .')'.
// mysql_error($this->link) .'<br><br>'.
// $s);
if (is_bool($result))
return TRUE;
if (mysql_num_rows($result) == 0)
return NULL;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$records[] = $row;
mysql_free_result($result);
break;
case 'MSSQL':
if (!($result = mssql_query($s, $this->link)))
$this->error('mssql_query()');
if (is_bool($result))
return TRUE;
if (mssql_num_rows($result) == 0)
return NULL;
while ($row = mssql_fetch_array($result, MSSQL_ASSOC))
$records[] = $row;
mssql_free_result($result);
break;
}
return $records;
}
public function affectedrows()
{
switch ($this->type) {
case 'MYSQL':
return mysql_affected_rows($this->link);
case 'MSSQL':
return mssql_rows_affected($this->link);
}
}
private function error($msg)
{
exit('<p style="font-family:verdana; ' .
'font-size:11px">' .
'<b>DATABASE OBJECT ERROR:</b><br>' .
'<em>Vennligst ta kontakt med admin.</em></p>');
//'<em>' . $msg . '</em></p>');
}
}
?>