<?php
/**
 * MySQL database abstraction library
 *
 * Severel db_ functions used for all database access to abstract the specifics of the database engine
 * used from the source of the project.
 * If all project files use this include file and functions the database of choice could be changed by changing
 * only this one file.
 *
 * @author Marnus van Niekerk
 * @package CMS
 * @subpackage GenPhpAdmin
 * @copyright 1999-2006 &copy; Marnus van Niekerk, used by permission
 * @see LIC-genadmin.php
 *
 */

/**
 * Uses setup.inc to sepeate database name, host, user and password from this file into seperate setup file
 * @see setup.inc
 */
require_once realpath(__DIR__ . "/../..") . "/setup.inc.php";

/**
 * Establishes a connection to a database
 *
 * Connects to the database using the default host, user, database and password unless these variables are passed
 *
 * @param string $db Database name                    - defaults to MYSQL_DB
 * @param string $host Host where database is located - defaults to MYSQL_HOST
 * @param string $user Username to use for connection - defaults to MYSQL_USER
 * @param string $pass Password to use for connection  -defaults to MYSQL_PASS
 * @return mixed Database link identifier
 * @see setup.inc
 */
function db_connect($db=MYSQL_DB, $host=MYSQL_HOST, $user=MYSQL_USER, $pass=MYSQL_PASS)
{

  // Connect to the database.
  $retval = mysqli_connect($host, $user, $pass);
  if (!$retval) {
    echo "Database connection error (" . mysqli_errno() . "): " . mysqli_error() . "<br />\n";
    exit;
  } else {

    // Select the current database.
    if (!mysqli_select_db($retval, $db)) {
      echo "Could not select database " . $db . ".<br />\n";
      echo "System error (" . mysqli_errno($retval) . "): " . mysqli_error($retval) . "<br />\n";
      exit;
    } else {

      // Success.
      return $retval;
    }
  }
}

/**
 *
 * Closes an active database connection
 *
 * Closes the active database connection pointed to by $linkID
 * @param mixed $linkID The database link ID of the link to close
 *
 */
function db_close(&$linkID)
{
  try {
    if (isset($linkID)) {
      mysqli_close($linkID);
      unset($linkID);
    }
  } catch (Exception $e) {
    echo "Exception raised in " . __FUNCTION__ . ".<br />\n";
    echo $e->getMessage() . "<br />\n";
    exit;
  }
  return 0;
}

/**
 * Runs a query on the database, returns a result set handle
 *
 * Runs the query passed in $query on the database connection specified by $linkID and returns
 * a result handle
 * @param string $query The query to run on the database
 * @param mixed $linkID The optional database link ID to use
 * @return mixed A result set handle
 *
 */
function db_query($sql, $linkID=-1, $debug = 0)
{

  // Create the query.
  try {
    $retval = mysqli_query($linkID, $sql);
    if (!db_query_valid($retval)) {
      echo "Invalid query (" . mysqli_errno($linkID) . "): " . mysqli_error($linkID) . "<br />\n";
//echo  get_resource_type($linkID) . "<br />\n";
//echo gettype($retval) . "<br />\n";
      echo "SQL = " . $sql . "<br />\n";
      exit;
    } else {

      // Done.
      return $retval;
    }
  } catch (Exception $e) {
    echo "Exception raised in " . __FUNCTION__ . ".<br />\n";
    echo $e->getMessage() . "<br />\n";
    echo "SQL = " . $sql . "<br />\n";
    exit;
  }
}

/**
 * Checks the return value from a db_query().
 */
function db_query_valid($retval)
{
  return ($retval === true) || (is_object($retval)) || is_resource($retval);
}

function db_execute($sql, $linkID)
{
  $lResult = false;
  $lQuery = db_query($sql, $linkID);
  if (db_query_valid($lQuery)) {
    db_free($lQuery);
    $lResult = true;
  }
  return $lResult;
}

/**
 * Fetch a row of data
 *
 * Fetches a row of data from a result handle, returns an associative array
 *
 * @param mixed $resID The result set handle to fetch a row from
 * @return array An associative array containg the database row from the result set
 */
function db_fetch($resID)
{
  try {
    return mysqli_fetch_array($resID, MYSQLI_ASSOC);
  } catch (Exception $e) {
    echo "Exception raised in " . __FUNCTION__ . ".<br />\n";
    echo $e->getMessage() . "<br />\n";
    exit;
  }
}

/**
 * Frees database memory
 *
 * Frees memory used by a result set (handle)
 *
 * @param mixed $resID The result set handle to free
 * @return bolean Succes or failure
 */
function db_free($resID)
{
  if (isset($resID) && ($resID !== true) && ($resID !== false)) {
    try {
      $retval = mysqli_free_result($resID);
      return $retval;
    } catch (Exception $e) {
      echo "Exception raised in " . __FUNCTION__ . ".<br />\n";
      echo $e->getMessage() . "<br />\n";
      exit;
    }
  }
}

/**
 * Number of rows
 *
 * The number of rows in a result set
 *
 * @param mixed $resID The result set handle to free
 * @return integer The number if rows in the result set
 */
function db_num_rows($resID)
{
  try {
    $retval = mysqli_num_rows($resID);
    return $retval;
  } catch (Exception $e) {
    echo "Exception raised in " . __FUNCTION__ . ".<br />\n";
    echo $e->getMessage() . "<br />\n";
    exit;
  }
}
function db_affected_rows($resID)
{
  try {
    $retval = mysqli_affected_rows($resID);
    return $retval;
  } catch (Exception $e) {
    echo "Exception raised in " . __FUNCTION__ . ".<br />\n";
    echo $e->getMessage() . "<br />\n";
    exit;
  }
}

/**
 * Auto insert ID
 *
 * The id of the last insert on AUTO_INCREMENT fields
 *
 * @param mixed $linkID The link ID of the datbase link the insert was done on
 * @return integer The key value from the auto insert
 */
function db_insert_id($linkID)
{
  $retval = mysqli_insert_id($linkID);
  return ($retval);
}

/**
 * Last error on the database
 *
 * Returns the error code and a description of the last error on the database connection
 * @param mixed $linkID Database link indentifier
 * @return string String containing the number and description of the last error
 */
function db_err($linkID=0)
{
  $retval = mysqli_errno($linkID) . ": " . mysqli_error($linkID);
  return $retval;
}

/**
 * Database seek
 *
 * Seek to position in result set
 * @param mixed $res The result set to seek in
 * @param integer $pos The position to seek to (default 0=start of result set)
 * @return void Nothing
 */
function db_seek($res, $pos=0)
{
  mysqli_data_seek($res, $pos);
}

/**
 * Column info
 *
 * Return an object with properties describing the field
 * Properties are:            <br>
 *      $retval->name       <br>
 *      $retval->table        <br>
 *      $retval->numeric  0/1   <br>
 *      $retval->primary_key  0/1   <br>
 *      $retval->unique_key 0/1   <br>
 *      $retval->multiple_key 0/1   <br>
 *      $retval->type       <br>
 *      $retval->unsigned 0/1   <br>
 *      $retval->blob   0/1   <br>
 *      $retval->not_null 0/1   <br>
 *      $retval->max_length 0/1   <br>
 *      $retval->zerofill 0/1   <br>
 * @param mixed $res Database result set handle
 * @param integer $pos The column to return info for
 * @return mixed An object with properties for each of the properties of the column
 */
function db_col_info($res)
{
  $retval = mysqli_fetch_field($res);
  return $retval;
}


function MysqlAutoid($cDBConnection, $id, $table)
{
  $query = 'SELECT MAX('.$id.') AS last_id FROM '.$table;
  $result = db_query($query, $cDBConnection);
  $idResult = mysqli_fetch_array($result);
  db_free($result);
  return $idResult['last_id']+1;
}
/// usage MysqlAutoid('nID','news');
?>
