Allinternal
Allinternal

Reputation: 37

Best way to check if Joomla! 3.4.0 article already exists

I am creating articles in Joomla! programmatically using JTable. Since I have a lot of articles that need to get synchronized periodically, I need to check each article if it already exists before inserting it (otherwise it produces errors).

What is the best way to do so?

My idea was to retrieve all articles from database and compare unique fields. But problems (blank page) occured while retreiving the articles. Here is the code:

function getExistingArticles(){

    // Create a new query object.
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);

    $query->select('*')->where('`a.created_by_alias`= `article_synchronizer`'); // Prepare query.

    $query->from('`#___categories` AS a');

    // Reset the query using newly populated query object.
    $db->setQuery($query);
    $articles = $db->loadObjectList(); // Execute query, return result list.

    return $articles;
}

If this is the "best" way in Joomla! to check if a certain article already exists, where is the problem in this code, that results in a blank page?

Otherwise which is the best way to check if a Joomla! article with a certain content already exists?

Upvotes: 2

Views: 691

Answers (1)

Lodder
Lodder

Reputation: 19733

I haven't tested your query, but I would suggest quoting column names and values using Joomla's API like so:

function getExistingArticles()
{
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);

    $query->select($db->quoteName(array('a.*')))
          ->from($db->quoteName('#__categories', 'a'))
          ->where($db->quoteName('a.created_by_alias') . ' = ' . $db->quote('article_synchronizer')); // Quoted query.

    $db->setQuery($query);
    $articles = $db->loadObjectList();

    return $articles;
}

I've fixed your query a little. You were using 3 underscores when defining the table prefix (only 2 should be used). The where and from clauses were also the wrong way round.

Upvotes: 1

Related Questions