<?php

function all($connect, $table, $fields, $queryFinal )
{
	$fields = (empty($fields)) ? (" * ") : ($fields);

	try{
		//return "select {$fields} from {$table} {$queryFinal}";
		$query = $connect->query("select {$fields} from {$table} {$queryFinal}");
		if ($query) {
			return $query->fetchAll();
		}
		else
		{
			return 'error';
		}
	} catch (PDOException $e){
		var_dump($e->getMessage());
		return 'error';
	}
}

function findItem($connect, $table, $fields, $searchField)
{
	$searchElements = '';
	foreach ($searchField as $key => $value) {
		$searchElements .= "{$key} = :{$key} AND ";
	}
 	$searchElements = rtrim($searchElements,'AND ');

	if(!empty($searchElements)){
		try{
			$query = "select {$fields} from {$table} WHERE {$searchElements}";
 			//return $query;
			$queryExecute = $connect->prepare($query);
			foreach ($searchField as $key => $value) {
				$queryExecute->bindParam(':'.$key, $value);
			}
			  
			$queryExecute->execute();
			$result = $queryExecute -> fetch();
			return $result;
		} catch (PDOException $e){
			var_dump($e->getMessage());
		}
	}
}


function query($connect, $tipo, $query )
{
	try{
		//return $query;exit;
 		$query = $connect->query( $query );
		//return $query->fetchAll();
		if ($query) {
			if($tipo == 'assoc'){
				return $query->fetchAll(\PDO::FETCH_ASSOC);
			}
			else
			{
				return $query->fetchAll();
			}
		}
		else
		{
			return 'error';
		}
	} catch (PDOException $e){
		var_dump($e->getMessage());
	}
}


function displayQuery($connect, $table, $fields, $queryFinal )
{

	return "select {$fields} from {$table} {$queryFinal}";
}
