Database access

Handle to database

First we must have a handel to the database


// Database setting
$db_hostaddr = "127.0.0.1";
$db_name = "demo";
$db_port = "5432";
$db_user = "demo1";
$db_pass = "demo7654321";


$dbconn = pg_connect("hostaddr=$db_hostaddr port=$db_port dbname=$db_name" .
                     " user=$db_user password=$db_pass  " .
		     " options='--application_name=$application_name'");

Very often we want an array of objects from the database.

So we define a small function for this


function rbis_db_query($dbconn, $query)
{

   $result = pg_query($dbconn, $query);

   if($result)
   {
      return NULL;
   }

   $rows = array();

   while($row = pg_fetch_assoc($result))
   {
      array_push($rows, $row);
   }

   return $rows;

}

And we can then use this like


$query = sprintf("select * from schema.table where .... limit 1000");

$rows = rbis_db_query($dbconn, $query);

Best practice is to always use a limit in the query.