Joomla database query SELECT AS - joomla

So I'm just hypothetically thrilled to be querying my hypothetical database:
$query->select($db->quoteName(array('user_id', 'name')));
I would, however, like the query to look like:
SELECT `user_id` AS `uid`, `name` AS `User-Name`
How the heck do I get the AS in there?

I know this question is 6 months old, so you've probably found an answer or worked around it, but for anyone else who has a similar problem:
$query->select($db->quoteName(array('user_id','name'),array('uid','User-Name')));
If you only want to use an alias for some fields, just pass null in the array for the fields you don't want to alias, so for example:
$query->select($db->quoteName(array('user_id','name'),array(null,'User-Name')));
would give
"SELECT `user_id`, `name` AS `User-Name`"

My preferred way is this:
I create an array with the fields I want to select:
$fields = array(
'a.id' => 'id',
'a.field1' => 'field1',
'a.field2' => 'field2',
'a.field3' => 'field3',
'b.field1' => 'bfield1',
'b.field2' => null,
'b.field3' => 'bfield3',
);
In the above array, the keys are used for the db Column names of the query, the values for the aliases, as you can see later in the $query->select().
*When you do not need an alias - just set null.
This helps better to control and check what fields I want and how to name them - and is better for maintenance or changes and is portable enough, as I only have to change my $fields array according to my needs.
Then the Joomla select command can be like:
$query->select( $db->quoteName(
array_keys($fields),
array_values($fields)
));
This will produce the following SQL SELECT query:
SELECT `a`.`id` AS `id`,`a`.`field1` AS `field1`,`a`.`field2` AS
`field2`,`a`.`field3` AS `field3`,`b`.`field1` AS
`bfield1`, `field2`, `b`.`field3` AS `bfield3`

Try the following:
$query->select($db->quoteName('user_id') .' AS '. $db->quoteName('name') .' AS '. $db->quoteName('User-Name'));
Be sure to use the full query as described here:
http://docs.joomla.org/Selecting_data_using_JDatabase
So yours will look something like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('user_id') .' AS '. $db->quoteName('name') .' AS '. $db->quoteName('User-Name'));
$query->from($db->quoteName('#__tablename'));
$db->setQuery($query);
$results = $db->loadObjectList();
Please note that I havent tested this query using AS so let me know if it works or not

I've got this to work:
->select($db->quoteName(array('user_id`' . ' AS ' . '`uid', 'name`' . ' AS ' . '`User-Name')))

It's better to use what Joomla! suggest us.
Note by putting 'a' as a second parameter will generate #__content AS a
So, you may have something like this:
$query
->select('*')
->from($db->quoteName('#__content', 'a'))

Related

Yii2 subquery GROUP BY in active record

can I convert this query
"SELECT * FROM (SELECT * FROM blog_post ORDER BY data DESC) blog_post GROUP BY blog_id LIMIT 2"
into a Yii2 active record query?
Thx
Ms
Yes, you can do this.
Yii2 gave us a wonderful library support.
You can form custom sql query and pass this query in findBySql() like:
$sql = "Some query/nested query";
$result = ModelClass::findBySql($sql);
Visit Yii official documentation.
BlogPost::find()
->orderBy('data DESC')
->groupBy('blog_id')
->limit(2)
->all();
I suppose you can do in this way :
Ⅰ:create a subQuery where you select from.
$blogPostQuery = BlogPostModel::find()->orderBy(['data' => SORT_DESC]);
Ⅱ:Get activeRecord results. The from params is an exist Query.
$models = (new yii\db\Query)
->from(['blog_post ' => $blogPostQuery])
->groupBy(['blog_id'])
->limit(2)
->all();
ps:
see yii\db\query->from()-detail in Yii Api;
(public $this from ( $tables )) $tables can be either a string (e.g. 'user') or an array (e.g. ['user', 'profile']) specifying one or several table names··· or a sub-query or DB expression
Have a try!I hope it`s useful for you:))

Laravel 3 Eloquent: Looking for a "where_nested()" example

I have a custom validation rule that is checking the DB for NULL.
I need to look for null or empty.
HAVE:
$query = $this->db()->table($table);
...
foreach( $null_columns as $col )
$query->where_null($col);
Which results in something like: SELECT * FROM t WHERE col1=foo AND col2 IS NULL
WANT:
SELECT * FROM t WHERE col1=blah AND (col2 = '' OR col2 IS NULL)
QUESTION:
Is where-nested() the right tool for the job?
If so, I'd really like to see an example.
If not, what's a good way to approach this?
Well, I ended up getting it to work this way:
$query = $this->db()->table($table);
...
foreach( $null_columns as $col )
{
$query->where(function($q) use($col){
$q->where($col,'=','');
$q->or_where_null($col);
});
}
... but would still like to see an example of using where_nested() to do this, if possible. I always appreciate learning something new :)

Concat in Codeigniter Active Record

I am trying a Concat for an autocomplete, Using CI's Active Record.
My Query is :
$this->db->select("CONCAT(user_firstname, '.', user_surname) AS name", FALSE);
$this->db->select('user_id, user_telephone, user_email');
$this->db->from('users');
$this->db->where('name', $term);
I keep getting an MySQL Error from this saying:
Error Number: 1054Unknown column 'name' in 'where clause'
Which is true, However I have just created in my Concat clause. I ideally need $term to match the Concatenated firstname and surname fields.
Any ideas what I can do to improve this? I am considering just writing this as an flat MySQL Query..
Thanks in advance
$this->db->select('user_id, user_telephone, user_email, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);
Not sure why you are running multiple selects. So just put it as a single select. It's probably that the 2nd one is overriding the first one and thus overwriting the concatenation to create the name column.
$this->db->select("CONCAT((first_name),(' '),(middle_name),(' '),(last_name)) as candidate_full_name");
Try like above 100% it will work in ci.
If cryptic solution doen't work then try it.
$query = "SELECT *
FROM (
SELECT user_id, user_telephone, user_email, CONCAT(user_firstname, ' ', user_surname) name
FROM users
) a
WHERE name LIKE '%".$term."%'";
$this->db->query($query);
Source: MySQL select with CONCAT condition
You have to SELECT the fields that you want concat like so:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);
This will also solve the issue:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname,user_surname) AS name', FALSE);
$this->db->from('users');

how to use 'like' instead of '=' in magento collection filter for custom module

i have managed to do this with addFieldToFilter default functionality like this:
$collection->addFieldToFilter(
array('first_name','last_name'),
array($post['firstName'],$post['lastName'])
);
this is working when i print sql (this is just part from the whole statement being printed):
((first_name = 'r') OR (last_name = 't'))
now i am trying to understand how to use 'like' instead of =.
need some help in understanding that.
your time and answers are highly appericiated thank you.
It's weird, but after some researching into your question the solution is quite simple - it's given in the comments in the Magento code:
In the comment for the method addAttributeToFilter() in Mage/Eav/Model/Entity/Collection/Abstract.php (which finally gets called) you can read:
/**
* Add attribute filter to collection
*
* If $attribute is an array will add OR condition with following format:
* array(
* array('attribute'=>'firstname', 'like'=>'test%'),
* array('attribute'=>'lastname', 'like'=>'test%'),
* )
*/
Wasn't quite clear to me what this was supposed to mean, but it's as simple: If you want to add an OR condition between the attributes in your statement, then you have to give your parameter for the addAttributeToFilter() method in this way, so in your case:
$collection->addFieldToFilter(
array(
array('attribute'=>'firstname', 'like'=>$post['firstName']),
array('attribute'=>'lastname', 'like'=>$post['lastName'])
));
You can follow this if you look inside the addAttributeToFilter() method:
if (is_array($attribute)) {
$sqlArr = array();
foreach ($attribute as $condition) {
$sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
$conditionSql = '('.implode(') OR (', $sqlArr).')';
For you googlers, the rigth way to to it is:
$collection->addFieldToFilter(
array('first_name','last_name'),
array(
array('like' => '%'.$post['firstName'].'%'),
array('like' => '%.'$post['lastName'].'%')
)
);
You should pass an array of fields and an array of conditions.
Generated SQL:
... WHERE ((first_name LIKE '%xxxx%') OR (last_name LIKE '%yyy%')) ...
addFieldToFilter( 'sku', array( "like"=>'abc123' ) )
Here you can read much more about Magento collections: http://alanstorm.com/magento_collections
For example, see section named "AND or OR, or is that OR and AND?" in this article.

CodeIgniter query syntax error

I am facing a syntax issue with a CodeIgniter database query. Can't figure out what's wrong.
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES (".$this->db->escape($_POST['email']).", ".$this->db->escape($lang).", ".$this->input->ip_address().")");
I am also looking for a way to output what the query looks like once the placeholders are replaced, as I am little confused with CodeIgniter debugging options.
It looks as though you are not escaping the strings that you're trying to input into the database. The query you've posted would evaluate to something like:
$query = $this->db->query("
INSERT IGNORE INTO table_name (email, lang, ip_address)
VALUES (email#email.com, en, 192.168.0.1)
");
This will throw an error as the strings in VALUES are not properly escaped. Instead of the query you're running you should use something like:
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')
");
Note the new ' characters around each string.
use
echo $this->db->last_query();
for retrieving the query runned.
so then check if the query is well formatted.
To know what query you are passing to your database. Use below statement and to insert data into the database. Please follow the below procedure.
echo $this->db->last_query();
$data = array(
'email' => $this->db->escape($_POST['email']),
'lang' = > $this->db->escape($lang),
'ip_address' => $this->input->ip_address(),
);
Call your model function $this->model->insert_function_name($data);
Your model function in your model file
public function insert_function_name($data)
{
$this->db->insert($table_name,$data);
return $this->db->insert_id();
}
Try this : your query was missing single quotes to the string type of value like email, lang and ip
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')");

Resources