How do I query a database?

Requested by Carnuke and Answered by Mithrandir on 2004/11/5 18:36:57

How do I query a database?

XOOPS has a database abstraction layer for you to use, when accessing the database.

The database object can be retrieved in two ways:
a) using the $xoopsDB instance - if you are in a function or class method, you will need to declare it global first with

global $xoopsDB;

b) calling a static getInstance() method on the Database class
$xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();


After that is done, you can use the database object to query the database
//Any statement goes in the query - SELECT, UPDATE, INSERT etc.
$result $xoopsDB->query('SELECT * FROM [...] ');
// if it is a SELECT statement, $result will now be a resultset so let's loop through it
while ($row $xoopsDB->fetchArray($result)) {
    
$variable $row['index'];
    
$another_variable $row['another_index'];
}

If the query is not a SELECT statement, $result will be true or false, depending on whether the SQL query encountered errors or not.

See also this FAQ here

This Q&A was found on XOOPS Web Application System : https://xoops.org/modules/smartfaq/faq.php?faqid=192