<?php

	/*
	function GetDataFromDB ( $sql, &$nbElems, $limit, $orderby )
	{
		$out = array();
		
		
		$conn = get_dbconnection();
	
		if ( $conn )
		{
			// Count
			
			$sqlcount = "select count(*) from (".$sql.") r";
			if ( $res = pg_query ( $conn, $sqlcount ) )
			{
				while ( $row = pg_fetch_row($res) )
				{
					$nbElems = $row [0];
				}
			}
			error_log ( "nbElems : " .$nbElems );
			
			
			// Run request
			error_log ( "request : " .$sql.$orderby.$limit );
			if ( $res = pg_query ( $conn, $sql.$orderby.$limit ) )
			{
				$cols = array ();
				
				for ( $i=0; $i<pg_num_fields ( $res ); $i++ )
				{
					$cols [$i] = pg_field_name ( $res, $i );
				}
				
				while ( $row = pg_fetch_row($res) )
				{
					$row1 = array();
					
					for ( $i=0; $i<count ($cols); $i++ )
					{
						$data = $row [ $i ];
						
						$row1 [ $cols[$i] ] = $data;
					}
					
					$out[] = $row1;
				}
			}
		}
		
		return $out;
	}
	*/


	function GetDataFromDB ( string $sql, int &$nbElems, string $limit = '', string $orderby = '' ) : array
	{
		$pdo = getPDO ();
    	$out = [];

    	try {
			$sqlcount 	= "SELECT COUNT(*) FROM ($sql) AS r";
			$stmt 		= $pdo->query($sqlcount);
			$nbElems 	= (int)$stmt->fetchColumn();
		//	$nbElems=0;
        
			$stmt 		= $pdo->query($sql . $orderby . $limit);
			$out 		= $stmt->fetchAll(PDO::FETCH_ASSOC);

    	} catch (PDOException $e){
        	error_log("Database error : " . $e->getMessage());
        	$out 		= [];
        	$nbElems 	= 0;
    	}

    	return $out;
	}
	
?>