k5n.us
X Home X X News X X Apps/Tools X X Support X X Downloads X X Articles X X Contact X
dbi4php
 AboutLicensingPlansAPITutorialDownloadDevelopersCompetitors  

dbi4php Tutorial

For real-life code, you can look at WebCalendar code. For example, the activity_log.php page or the approve_entry.php page.

The dbi4php interface is very simple to use. In most apps, you will want to isolate your dbi_connect and dbi_close calls into a function call. Additionally, you may want to load your database settings (hostname, login, password, database) from a data file. (Look at the WebCalendar code for an example of this.



Open, Query and Close:


<?php
// Db settings
$db_type = 'mysql';
$db_host = 'localhost';
$db_login = 'webcalendar';
$db_password = 'webcal01';
$db_database = 'intranet';

// Include dbi4php file
require_once 'dbi4php.php';

print "<html><body><h1>Simple Demo</h1>\n";

// Open db connection
$c = dbi_connect ( $db_host, $db_login,
  $db_password, $db_database );
if ( ! $c ) {
  print "Error connecting to database: " . dbi_error () .
    "</body></html>\n";
  exit;
}

// Execute SQL query
$res = dbi_query ( "SELECT name FROM users ORDER BY name" );
if ( ! $res )  {
  print "Database error: " . dbi_error () .
    "</body></html>\n";
  exit;
}

print "<ul>\n";

// Loop: get each row
while ( $row = dbi_fetch_row ( $res ) ) {
  // Print out user(row)
  print "<li>" . htmlspecialchars ( $row[0] ) .
    "</li>\n";
}

print "</ul>\n";

// Free result from dbi_query
dbi_free_result ( $res );

// Close connection
dbi_close ( $c );

print "</body></html>\n";
?>


Using dbi_execute with URL parameter:


<?php
// Include dbi4php file
require_once 'dbi4php.php';
// Include common php file that sets db parameters and opens
// db connection
require_once 'startup.php';

$error = '';

print "<html><body><h1>Demo</h1>\n";

// Get "id" parameter if passed in with URL and
// make sure it is just an integer
$id = $_GET['id'];
if ( empty ( $id ) )
  $error = 'No user id specified';
else if ( ! preg_match ( "/^\d+$/", $id ) ) {
  $error = 'Invalid id';
}

if ( empty ( $error ) ) {
  // Build SQL for use in dbi_execute
  $sql = 'SELECT name FROM user WHERE id = ?';
  $params = arary ( $id );
  // Execute query
  $res = dbi_execute ( $sql, $params )
  if ( $res ) ) {
    echo "<p>\n";
    if ( $row = dbi_fetch_row ( $res ) ) {
      echo "User name: " . htmlspecialchars ( $row[0] );
    } else {
      $error = "No such user";
    }
    echo "</p>\n";
    dbi_free_result ( $res );
  } else {
    $error = "Database error: " . dbi_error ();
  }
}

if ( ! empty ( $error ) ) {
  echo "<h2>Error</h2><p>" . $error . "</p>\n";
}

echo "</body></html>\n";
// Close connection in common file
require_once 'shutdown.php';
?>


SourceForge.net Logo

Valid XHTML 1.0 Valid CSS PHP
Page Last Updated: 20-Jan-2009
Copyright ©2004-2017 k5n.us, All Rights Reserved