<?php
class MySqlConnection{
	private $dbh;
	function __construct(){
		$dsn = "mysql:host=localhost;dbname=mueb_cotizador;charset=utf8mb4";
		//$dsn = "mysql:host=localhost;dbname=bd_cotizador;charset=utf8mb4";
		$options = [
			PDO::ATTR_EMULATE_PREPARES   => false,
			PDO::ATTR_EMULATE_PREPARES => true,
			PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
			PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
		];
		$this->dbh = new PDO($dsn, 'mueb_usr', 'Cotizador2022@', $options);
		//$this->dbh = new PDO($dsn, 'root', '', $options);
	}

	function ExecuteReader($q){
		try{
			$sth = $this->dbh->prepare($q);
			$sth->execute();
			$sth->setFetchMode(PDO::FETCH_ASSOC);
			$result = $sth->fetchAll();
			$this->dbh = null;
			return $result;
		}
		catch(PDOException $e){
			error_log('PDOException - ' . $e->getMessage(), 0);
			http_response_code(500);
			return $e->getMessage();
			//die($e->getMessage());
		}
	}

	function ExecuteQuery($q, $parametros){
		try	{
			$sth = $this->dbh->prepare($q);
			$sth->execute($parametros);
			$this->dbh = null;
			return "ok";
		}
		catch(PDOException $e){
			error_log('PDOException - ' . $e->getMessage(), 0);
			http_response_code(500);
			//die($e->getMessage());
			return $e->getMessage();
		}
	}
	function ExecuteQueryB($q, $parametros){
		try	{
			$sth = $this->dbh->prepare($q);
			$sth->execute($parametros);
			//$this->dbh = null;
			return "ok";
		}
		catch(PDOException $e){
			error_log('PDOException - ' . $e->getMessage(), 0);
			http_response_code(500);
			//die($e->getMessage());
			return $e->getMessage();
		}
	}

	function getLastID($q, $parametros){
		try	{
			$sth = $this->dbh->prepare($q);
			$sth->execute($parametros);
			$id = $this->dbh->lastInsertId();
			$this->dbh = null;
			return $id;
		}

		catch(PDOException $e){
			error_log('PDOException - ' . $e->getMessage(), 0);
			http_response_code(500);
			//die($e->getMessage());
			return $e->getMessage();
		}
	}
}
?>
