Question

Here is the SQL statement that is working for me:

SELECT inl_cbsubs_subscriptions.user_id, inl_cbsubs_payment_items.subscription_id, inl_cbsubs_payment_items.stop_date, inl_cbsubs_payment_items.id FROM inl_cbsubs_subscriptions INNER JOIN inl_cbsubs_payment_items ON inl_cbsubs_subscriptions.id=inl_cbsubs_payment_items.subscription_id WHERE inl_cbsubs_subscriptions.user_id=596 ORDER BY id DESC LIMIT 1;

Here is my attempt of formatting this same query for Joomla:

$db2 = JFactory::getDbo();
$stopDateQuery = $db2->getQuery(true);

$stopDateQuery->select($db2->quoteName(array('#__cbsubs_subscriptions.user_id', '#__cbsubs_payment_items.subscription_id', '#__cbsubs_payment_items.stop_date')));
$stopDateQuery->from($db2->quoteName('#__cbsubs_subscriptions'));
$stopDateQuery->innerJoin($db->quoteName('#__cbsubs_payment_items') . ' ON #__cbsubs_subscriptions.id = #__cbsubs_payment_items.subscription_id');
$stopDateQuery->where($db2->quoteName('#__cbsubs_subscriptions.user_id')." = ".$db2->quote($myId));
$stopDateQuery->ORDER BY($db2->quoteName('#__cbsubs_payment_items.id'));
$stopDateQuery->DESC LIMIT 1;

I have tested the Joomla formatting and can get it to work if I remove the last two lines:

$stopDateQuery->ORDER BY($db2->quoteName('#__cbsubs_payment_items.id'));
$stopDateQuery->DESC LIMIT 1;

This tells me that the formatting problem is in that location. It is a requirement that I add these additional filters to the query, so where did I go wrong with it?

Was it helpful?

Solution

Try using the following (for Joomla 3.x+)

$stopDateQuery->order($db2->quoteName('#__cbsubs_payment_items.id') . 'DESC');
$stopDateQuery->setLimit(1);

If you're using Joomla 2.5, then use this to set the limit

$db2->setQuery($stopDateQuery,0,1);  

OTHER TIPS

As long as sql injection is not possible you can simply do this:

$stopDateQuery = "SELECT inl_cbsubs_subscriptions.user_id, inl_cbsubs_payment_items.subscription_id, inl_cbsubs_payment_items.stop_date, inl_cbsubs_payment_items.id FROM inl_cbsubs_subscriptions INNER JOIN inl_cbsubs_payment_items ON inl_cbsubs_subscriptions.id=inl_cbsubs_payment_items.subscription_id WHERE inl_cbsubs_subscriptions.user_id=596 ORDER BY id DESC LIMIT 1";

It gets run a little faster too.

If sql injection is possible then you can use

$db2->quoteName($id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top