Monday, September 17, 2007

Fetching data from database

In today's post I will present basic ways of fetching data from database in LIZ DB.


For fetching data from database there are three different functions, these are:
  • public function SelectOne() - fetches a record, returns an associative array that represents given record
  • public function Select() - fetches a set of records, returns an array of associative arrays (records)
  • public function SelectColumn() - fetches a set of given column's values, returns an array of column's values
Before invoking any of the Select functions, public field Query should be set to valid SELECT statement otherwise LIZ DB will throw LIZDBException.
LIZDBException exception will be also thrown if Query will contain other statements than SELECT (like INSERT, CREATE, DROP, etc.).

Examples of usage.

Example 1. Fetching single records.
$db->Query = 'SELECT * FROM `lizdb_test_table` ORDER BY id DESC LIMIT 1';
$record = $db->SelectOne();

// $record is an associative array
echo 'Last record is: ';
echo $record['id'] . ', ' . $record['char_column'] . ', ' . $record['int_column'] . ', ' .$record['double_column'];
Example 2. Fetching sets of records.
$db->Query = 'SELECT * FROM `lizdb_test_table`';
$records = $db->Select();

// $records is an array of associative arrays
foreach($records as $r) {
echo $r['id'] . ', ' . $r['char_column'] . ', ' . $r['int_column'] . ', ' .$r['double_column'];
Example 3. Fetching sets of given column's values.
$db->Query = 'SELECT `double_column` FROM `lizdb_test_table` WHERE `double_column` < negativedoubles =" $db-">SelectColumn();

// $negativeDoubles is an ordinary array
echo 'negative doubles are:' . implode(',', $negativeDoubles);

2. Live examples

Live examples are available at LIZ DB - SELECT API Examples

No comments: