<?php
include_once("DBConnection.inter.php");

/**
 * MySQL implementation
 */
class MySQLNative implements DBConnection
{
	private $dbh = null;
	
	//Connection settings
	private $server;
	private $base;
	private $user;
	private $password;
	
	/**
	 * Constructeur
	 * 
	 * @param (String) serveur
	 * @param (String) username
	 * @param (String) password
	 * @param (String) databse
	 */
	
	public function __construct($server ,$username, $password, $database) {
		$this->server = $server;
		$this->user = $username;
		$this->password = $password;
		$this->base = $database;
		
		$this->connection();
	}
	
	/**
	 * Retourne le nom du type de connexion utilise
	 * 
	 * @return (String)
	 */
	
	public function getDBName() {
		return "mysql";	
	}
	
	/**
	 * Effectue la connexion
	 */
	
	public function connection() {
		$this->dbh = mysql_connect($this->server,$this->user,$this->password);
		mysql_select_db ($this->base,$this->dbh);
	}
	
	/**
	 * Déconnexion de la base de donnée
	 */
	
	public function disconnect() {
		mysql_close($this->dbh);
	}
	
	/**
	 * Exécuter un requête
	 */
	
	public function execQuery($sql,array $parameters=array()) {
		$sth = null;
		$sqlparts = explode("?",$sql);
		$nbNeeded = count($sqlparts)-1;
		$nbValues = count($parameters);
		if($nbNeeded == $nbValues)
		{
			$sqlfinal = "";
			for($x=0;$x<count($parameters);$x++)
			{
				$sqlfinal .= $sqlparts[$x] . "'" . 
					mysql_real_escape_string($parameters[$x], $this->dbh) . "'";
			}
			$sqlfinal = $sqlfinal . $sqlparts[count($sqlparts)-1];
			
			$sth = mysql_query($sqlfinal,$this->dbh);
			
			if(!$sth)
			{
				trigger_error("Invalid query: " . mysql_error(), E_USER_ERROR);
				return;
			} 
		}
		else
		{
			trigger_error("The number of parameters is invalid (".$nbValues.") "
				.$nbNeeded." needed",E_USER_ERROR);
			return;
		}
		return $sth;
		
	}
	
	public function execQuerySelect($sql,array $parameters=array()) {
		$sth = $this->execQuery($sql,$parameters);
		$res = array();
		$x = 0;
		while($line = mysql_fetch_assoc($sth)) {
			$res[$x] = $line;
			$x++;
		}
		return $res;
	}
	
	public function execQueryIterator($sql,array $parameters=array()) {
		$sth = $this->execQuery($sql,$parameters);
		
		return new MySQLNativeIterator($sth);
	}
	
	public function getLastInsertId() {
		return mysql_insert_id($this->dbh); 
	}
	
	public function getNumberAffectedRow() {
		return mysql_affected_rows($this->dbh);
	}
}

/**
 * Iterator version MySQLNative
 */
class MySQLNativeIterator implements DBIterator {
	private $sth;
	public function __construct($sth) {
		$this->sth = $sth;
	}
	
	public function getNext() {
		return mysql_fetch_assoc($this->sth);
	}
}

?>