sammela.com header image 2

Database Access in OpenCart

November 16th, 2009 · No Comments · Uncategorized

The OpenCart Ecommerce software package is designed for database portability.

PHP, the native language of OpenCart, contains built in functions that are specific to different sql implementations, such as MySql, but these absolutely should not be used in any modules or add-ons that are written for OpenCart.

Instead, the DB class should be used, to preserve database portability.

The DB class is located in the db.php file contained in the system/library/ directory, under the OpenCart application directory.

The following example shows how the DB class is used to look at the contents of the setting database table and the coupon database table with its related coupon_description table.

The DB class provides a standard database implementation independent interface for the rest of the OpenCart application software.

constructor Accepts the following parameters: $hostname, $username, $password, $database.Sets up a connection to the database.
destructor Destroys the connection to the database.
query Accepts a query, called $sql.  Queries the database and returns the result, but does some other cool things too.  If the result fromt the query is a database “resource”, this method reads all the rows from the resource, and returns them in an object that contains both and array of the database rows and the count of the database rows.  See example later in this article.
escape Makes data safe to insert in the database by prepending backslashes to unsafe characters such as single quote, double quote, and others.  See the PHP documentation on the  mysql_real_escape_string function, for more detail.
countAffected Returns the number of affected rows in the previous query.
getLastId Returns an id generated for the auto increment column from the most recent insert, or 0 if the previous query did not result in a new auto increment.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Create the $db object of the DB Class
$db     = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);


// Query the contents of the setting table
$query  = $db->query("SELECT * FROM " . DB_PREFIX . "setting");

// Display the results of the query
foreach ($query->rows as $setting) {
    echo($setting['key']." ".$setting['value']."<br />");
}

// Query the contents of the coupon table left joined to the coupon_description table
$coupon_query = $db->query("SELECT * FROM " . DB_PREFIX . "coupon c LEFT JOIN " . DB_PREFIX . "coupon_description cd ON (c.coupon_id = cd.coupon_id) WHERE c.status = '1'");

// Display the results of the query
foreach ($coupon_query->rows as $coupon)
{
    echo("<pre>"); print_r($coupon); echo("</pre>");
}

 

© 2009, Sam Mela. All rights reserved.

Tags:

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment