3 simple classes that handle database interaction and results - written in PHP4. SystemObject loads your DB access information into class vars. DBConnect directly interacts with the DB in multiple ways (connect, query, escapeString, affectedRows, ect.). DBResult fetches the results (fetch, fetchOne, NumRows).SystemObject.php:
<?php // vim: expandtab sw=4 ts=4 fdm=marker
/**
* Place to hold information to be used by the whole CMS.
*
* @var $db database name
* @var $dbuser username to log into database
* @var $dbpass password to log into database
* @var $dbhost the address of the database (localhost, mysql.domain.com)
*
* The following work is licensed under a Creative Commons
* Attribution-NonCommercial 2.5 License. For more
* information on this license go to http://creativecommons.org/licenses/by-nc/2.5/
*/
class SystemObject
{
/* {{{attributes */
/**
* Vars to hold the DB access info - guess could put it into an array
*/
var $db;
var $dbuser;
var $dbpass;
var $dbhost;
/* }}}attributes */
/* {{{constructor */
/**
* Constructor
*/
function SystemObject()
{
/*
* Tell me where you are keeping the DB access info so I can go and get it.
* Maybe one day figure out how to get it from a config file. Needless to
* say the database access information is defined in the DBInfo.php page.
* define("DATABASE_NAME","db");
*
* Reason for doing it this way - I DO NOT want my database access information
* anywhere on the web root.
*/
require_once('path\to\DBInfo.php');
$this->db = DATABASE_NAME;
$this->dbuser = DATABASE_USER;
$this->dbpass = DATABASE_PASS;
$this->dbhost = DATABASE_HOST;
}
/* }}}constructor */
}
?>
DBConnect.php:
<?php // vim: expandtab sw=4 ts=4 fdm=marker
/**
* a simple DB connection class that I am writing completely only on my own.
* Well maybe not completely. I have been looking at various classes written
* by others (the phpc class by Ben Ramsey and another class provided by a
* tutorial) for inspiration. This class should hopefully allow for the
* connection and selection of a MySQL DB, as well as a way to query it and get
* back an array result resource.
*
* @var $link
* @var $query
* @var $result
*
* @uses DBResult
*
* The following work is licensed under a Creative Commons
* Attribution-NonCommercial 2.5 License. For more
* information on this license go to http://creativecommons.org/licenses/by-nc/2.5/
*/
/* This assumes that the SystemObject.class.php file is in the same directory */
require_once 'SystemObject.class.php';
class DBConnect extends SystemObject
{
/* {{{attributes */
/**
* Link to the database
*/
var $link;
/**
* Query to be sent to the database
*/
var $query;
/**
* Result resource
*/
var $result;
/* }}}attributes */
/* {{{constructor */
function DBConnect()
{
parent::SystemObject();
$this->link = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
if($this->link == FALSE)
{
return FALSE;
}
if(!mysql_select_db($this->db, $this->link))
{
return FALSE;
}
return TRUE;
}
/* }}}constructor */
/* {{{query */
function &query($sql='')
{
$result = mysql_query($sql, $this->link);
if($result != FALSE)
{
$this->result = new DBResult(&$result);
return $this->result;
}
else
{
return $result;
}
}
/* }}}query */
/* {{{affectedRows */
/**
* Number of rows affected by the query.
* An integer is returned or -1 on failure.
*/
function affectedRows()
{
return mysql_affected_rows($this->link);
}
/* }}}affectedRows */
/* {{{lastInsertId */
/**
* The ID generated for an AUTO_INCREMENT column by the previous
* INSERT query. Returns the ID or 0 if the previous
* query does not generate an AUTO_INCREMENT value, or FALSE if
* no MySQL connection was established.
*/
function lastInsertId()
{
return mysql_insert_id($this->link);
}
/* }}}lastInsertId */
/* {{{escapeString */
/**
* This will escape a string for insertion into the MySQL database.
* Returns the escaped string, or FALSE on error.
*/
function escapeString($string)
{
return mysql_real_escape_string($string);
}
/* }}}escapeString */
/* {{{close */
function close()
{
return mysql_close($this->link);
}
/* }}}close */
}
?>
DBResult.php:
<?php // vim: expandtab sw=4 ts=4 fdm=marker
/**
* provides a means to get the database results as well as other misc. information
* This class provides a means for the user to fetch the database results by various
* methods. It will also allow the user to retreive various misc. information
* pertaining to that result set.
*
* @var result
*
* The following work is licensed under a Creative Commons
* Attribution-NonCommercial 2.5 License. For more
* information on this license go to http://creativecommons.org/licenses/by-nc/2.5/
*/
class DBResult
{
/* {{{attributes */
/**
* Holds the result resource from the query
*/
var $result;
/* }}}attributes */
/* {{{constructor */
/**
* Get the result resource. A reference to the ressult set is expected.
*/
function DBResult(&$result)
{
$this->result = $result;
}
/* }}}constructor */
/* {{{fetch */
/**
* Fetch a row of the results from the query into an array. Both the
* associative and numerical indexes are available. A reference to the
* array is returned or FALSE if there are no more rows.
*/
function &fetch()
{
return mysql_fetch_array($this->result);
}
/* }}}fetch */
/* {{{fetchObject */
/**
* Fetch a row of the results from the query into an object. A reference to the
* object is returned or FALSE if there are no more rows.
*
*/
function &fetchObject()
{
return mysql_fetch_object($this->result);
}
/* }}}fetchObject */
/* {{{fetchOne */
/**
* Fetch the data in the first cell of the first column. A reference
* to the data is returned or FALSE on failure.
*/
function &fetchOne()
{
return mysql_result($this->result, 0);
}
/* }}}fetchOne */
/* {{{numRows */
/**
* Number of rows in the result set. An integer is returned or
* FALSE on failure.
*/
function numRows()
{
return mysql_num_rows($this->result);
}
/* }}}numRows */
}
?>
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Database Code Articles
More By lig
developerWorks - FREE Tools! |
Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time. FREE! Go There Now!
|
|
|
|
Achieving true agility is a never-ending effort. We will showcase how you can become agile incrementally, a few practices at the time.Which practices should any agile team strive to adopt? What additional practices should you consider based on your needs to scale? Adopting practices are however made much easier with the right tool support. What about if your tools adapt to your practices? We will take a look at how the Jazz technology can be leveraged to make your process change the behavior of your tools. FREE! Go There Now!
|
|
|
|
Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager. FREE! Go There Now!
|
|
|
|
Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase. FREE! Go There Now!
|
|
|
|
XML has become a common way of storing business data as flat files and many data server vendors including IBM have provided ways to store this data within relational database systems. Increasingly collections of XML files are accessed like databases using an xQuery and other XML standard mechanisms. Businesses find the need to combine the traditional tabular structured data with XML formatted data. In this webcast, you’ll learn about IBM’s WebSphere Federation Server technology, which provides users with the ability to integrate these two data formats. FREE! Go There Now!
|
|
|
|
Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast. FREE! Go There Now!
|
|
|
|
Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms. FREE! Go There Now!
|
|
|
|
Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs). FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to try the IBM SOA Sandbox for connectivity. The SOA Sandbox for connectivity provides a trial environment with the tooling and components to help you explore how to effectively connect your infrastructure and integrate all of the people, processes and information in your company. Use the hosted sandbox to explore SOA techniques that streamline connecting existing IT assets together, as well as learn how to connect them to new business logic. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |