2

I have written a database query, like so:

$query = $db->getQuery(true)
    ->select("u.*,ju.username,ju.email,ju.lastvisitDate as last_login")
    ->from("#__component_users AS u")
    ->leftJoin("#__users AS ju ON ju.id = u.uid");

How can I quote items in select clause, especially when there is an alias?

1 Answer 1

3
$db->quoteName(mixed $name, mixed $as = null)

https://api.joomla.org/cms-3/classes/JDatabaseQuery.html#method_quoteName

With the quoteName-function you can quote column names. It accepts strings and arrays. A simple quote with alias (the AS) would look like:

$db->quoteName('ju.lastvisitDate', 'last_login')

$as (the second parameter) is always optional. So if you don't want to give your column an alias just write

$db->quoteName('ju.lastvisitDate')

With an array it would like this:

$db->quoteName(array('ju.email', 'ju.lastvisitDate'), array(null, 'last_login'))

Note the null value in the second array if you don't want to give a column an alias.

As long as you don't use any reserved keywords or variables (e.g. submitted by the user) as column names I would not escape them. See also this: https://docs.joomla.org/Secure_coding_guidelines#Secure_field_names

2
  • @user3533235 this is a clear, correct, and comprehensive answer. Unless you require further explanation about something, please award the green tick to this answer so that this page is deemed resolved.
    – mickmackusa
    Jan 27, 2019 at 11:38
  • @user3533235 Please accept this answer.
    – mickmackusa
    Jul 10, 2020 at 0:34

Your Answer

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

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