Работа с базой данных в Joomla 2.5
Подключение к базе данных:
$db = JFactory::getDbo();
Также используется и в файле модели.
Получение экземпляра класса JDatabaseQuery:
$query = $db->getQuery(true);
Выбор данных из одной таблицы:
// Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Select all records from the user profile table where key begins with "custom.". // Order it by the ordering field. $query->select(array('user_id', 'profile_key', 'profile_value', 'ordering')); $query->from('#__user_profiles'); $query->where('profile_key LIKE \'custom.%\''); $query->order('ordering ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results as a list of stdClass objects. $results = $db->loadObjectList();
Выбор данных из двух таблиц:
// Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Select all articles for users who have a username which starts with 'a'. // Order it by the created date. $query ->select(array('a.*', 'b.username', 'b.name')) ->from('#__content AS a') ->join('INNER', '#__users AS b ON (a.created_by = b.id)') ->where('b.username LIKE \'a%\'') ->order('a.created DESC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results as a list of stdClass objects. $results = $db->loadObjectList();
Выбор данных из больше чем двух таблиц:
$query ->select(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*')) ->from('#__content AS a') ->join('INNER', '#__users AS b ON (a.created_by = b.id)') ->join('LEFT', '#__user_profiles AS c ON (b.id = c.user_id)') ->join('RIGHT', '#__categories AS d ON (a.catid = d.id)') ->where('b.username LIKE \'a%\'') ->order('a.created DESC');
Вставка записи
с помощью SQL:
// Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Insert columns. $columns = array('user_id', 'profile_key', 'profile_value', 'ordering'); // Insert values. $values = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1); // Prepare the insert query. $query ->insert($db->quoteName('#__user_profiles')) ->columns($db->quoteName($columns)) ->values(implode(',', $values)); // Reset the query using our newly populated query object. $db->setQuery($query); Задали sql запрос, теперь его выполняем: try { // Execute the query in Joomla 2.5. $result = $db->query(); } catch (Exception $e) { // catch any database errors. }
Для Joomla Framework 12.1 и выше:
try { // Execute the query in Joomla 3.0. $result = $db->execute(); } catch (Exception $e) { // catch any database errors. }
с помощью объекта записи:
// Create and populate an object. $profile = new stdClass(); $profile->user_id = 1001; $profile->profile_key='custom.message'; $profile->profile_value='Inserting a record using insertObject()'; $profile->ordering=1; try { // Insert the object into the user profile table. $result = JFactory::getDbo()->insertObject('#__user_profiles', $profile); catch (Exception $e) { // catch any errors. }
Обновление записи
с помощью SQL:
$db = JFactory::getDbo(); $query = $db->getQuery(true); // Fields to update. $fields = array( 'profile_value=\'Updating custom message for user 1001.\'', 'ordering=2'); // Conditions for which records should be updated. $conditions = array( 'user_id=42', 'profile_key=\'custom.message\''); $query->update($db->quoteName('#__user_profiles'))->set($fields)->where($conditions); $db->setQuery($query); try { $result = $db->query(); // Use $db->execute() for Joomla 3.0. catch (Exception $e) { // Catch the error. }
с помощью объекта:
// Create an object for the record we are going to update. $object = new stdClass(); // Must be a valid primary key value. $object->id = 1; $object->title = 'My Custom Record'; $object->description = 'A custom record being updated in the database.'; try { // Update their details in the users table using id as the primary key. $result = JFactory::getDbo()->updateObject('#__custom_table', $object, 'id'); } catch (Exception $e) { // catch the error. }
Удаление записи:
$db = JFactory::getDbo(); $query = $db->getQuery(true); // delete all custom keys for user 1001. $conditions = array( 'user_id=1001', 'profile_key LIKE \'custom.%\''); $query->delete($db->quoteName('#__user_profiles')); $query->where($conditions); $db->setQuery($query); try { $result = $db->query(); // $db->execute(); for Joomla 3.0. } catch (Exception $e) { // catch the error. }
Транзакция:
$db = JFactory::getDbo(); try { $db->transactionStart(); $query = $db->getQuery(true); $values = array($db->quote('TEST_CONSTANT'), $db->quote('Custom'), $db->quote('/path/to/translation.ini')); $query->insert($db->quoteName('#__overrider')); $query->columns($db->quoteName(array('constant', 'string', 'file'))); $query->values(implode(',',$values)); $db->setQuery($query); $result = $db->query(); $db->transactionCommit(); } catch (Exception $e) { $db->transactionRollback(); // catch any database errors. }