17

Suppose you have constructed a query with Joomla.

// 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($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'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 (see later for more options on retrieving data).
$results = $db->loadObjectList();

Example from here: https://docs.joomla.org/Selecting_data_using_JDatabase

Is there a command to print out the query statement (not the results the but actual SQL)?

2
  • So that I can read the query as "SELECT * FROM .... "
    – Mat Kay
    Commented Sep 18, 2015 at 0:21
  • 1
    why not use the debug mode?
    – jdog
    Commented Sep 18, 2015 at 2:26

6 Answers 6

23

you need to echo __toString()

echo($query->__toString());

you can fing more info here

https://docs.joomla.org/API16:JDatabaseQuery/_toString

Hope it helps

2
  • Would just like to note that when using this method, it dumps the query with the Joomla prefix #__.
    – Lodder
    Commented Oct 6, 2015 at 15:20
  • 1
    echo (string) $query;
    – JProof
    Commented Apr 20, 2016 at 6:19
10

You can also use Joomla's replacePrefix function which dumps out the query in a format that can be inserted straight into the likes of PhpMyAdmin.

Here's an example:

$db = JFactory::getDbo();

$query = $db->getQuery(true);
$query->select($db->quoteName('something'))
      ->from($db->quoteName('#__content')); 
$db->setQuery($query);

// Dump the query
echo $db->replacePrefix((string) $query);

Will output the following:

SELECT `something` FROM `jos_content`
6

You can also use native dump() method: echo $query->dump();

2
  • I prefer using this one since it will print the db prefix as well.
    – hans2103
    Commented Sep 1, 2020 at 9:03
  • This method does not work anymore. dump() is deprecated without replacement
    – hans2103
    Commented Jul 17, 2023 at 12:15
5

The JDatabaseQuery object has a __toString() function that outputs the query so you can do:

echo $db->getQuery();

Or if you want to pass it to a function you can explicitly cast it to a string first:

var_dump((string)$db->getQuery());
0

The Joomla debug feature will give you a lot of information about the queries that are executed when your website loads.

0
echo $query;

will do fine.

this makes use of this code

echo($query->__toString());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.