<?php

		
	function GetDataFromDB ( $sql, &$nbElems, $limit, $orderby )
	{
		$out = array();
		
		
		$conn = get_dbconnection();
	
		if ( $conn )
		{
			// Count
			
			$sqlcount = "select count(*) from (".$sql.") r";
			// error_log ( "sqlcount : " .$sqlcount );
			if ( $res = pg_query ( $conn, $sqlcount ) )
			{
				while ( $row = pg_fetch_row($res) )
				{
					$nbElems = $row [0];
				}
			}
						
			
			// Run request
			// if ( $res = pg_query ( $conn, $sql.$orderby.$limit ) )
			$request = $sql.$orderby.$limit;
			// error_log ( "request : " .$request );
			if ( $res = pg_query ( $conn, $request ) )
			{
				$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;
	}
	
?>