DataLib Examples
Version 0.6beta
Sean Finkel
First, we will be connecting to a MySQL database, hosted on "localhost". Next, assume we have these tables:
Categories |
|
---|---|
Column Name | Column Type |
cat_id | integer |
cat_name | varchar(20) |
News | |
---|---|
Column Name | Column Type |
news_id | integer |
news_title | varchar(30) |
news_body | text |
cat_id | integer |
Our first example is a simple data retrieval and display. We will grab all the news items and what category they are in and display the data.
<?php
include 'include/datalib.php';
$db_conn =& DlDatabase::NewConnection('MySQL', 'root', '', 'test_database', 'localhost');
if (!$db_conn->Open()) {
die ($db_conn->GetError());
}
$rs =& DlRecordset::NewRecordset($db_conn);
$rs->Open('select news_title, news_body, cat_name from news, categories where categories.cat_id = news.cat_id order by news_title');
$rs->MoveFirst();
while (!$rs->Eof()) {
echo $rs->Value('news_title') ' - ' . $rs->Value('cat_name') . '<br />' . $rs->Value('news_body') . '<br /><br />';
$rs->MoveNext();
}
?>
This is the most common instance of database interaction in PHP. In order to execute queries that don't return result sets, it is recommended you use the Execute method of the database object. While Datalib provides an interface to add new rows, update data and remove rows without dealing with the SQL directly, it is extremely limited and not very efficient in a web environment. By the final release (v1.0) this functionality will be removed as it is uneccesary.