Does CDbcommand method queryAll() in yii return indexed entries only? - yii

I am trying to retrieve data from a simple mySql table tbl_u_type which has just two columns, 'tid' and 'type'.
I want to use a direct SQL query instead of the Model logic. I used:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('type')->from('tbl_u_type')->queryAll();
return $userArray;
But in the dropdown list it automatically shows an index number along with the required entry. Is there any way I can avoid the index number?

To make an array of data usable in a dropdown, use the CHtml::listData() method. If I understand the question right, this should get you going. Something like this:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('tid, type')->from('tbl_u_type')->queryAll();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($userArray,'tid','type'));
You can also do this with the Model if you have one set up for the tbl_u_type table:
$users = UType::model()->findall();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($users ,'tid','type'));
I hope that gets you on the right track. I didn't test my code here, as usual, so watch out for that. ;) Good luck!

Related

CodeIgniter4 Model returning data results

I am starting to dabble in CI4's rc... trying to get a head of the game. I noticed that the Model is completely rewritten.
Going through their documentation, I need some guidance on how to initiate the equivalent DB query builder in CI4.
I was able to leverage return $this->findAll(), etc...
however, need to be able to be able to query w/ complex joins and also be able to return single records etc...
When trying something like
return $this->orderBy('import_date', 'desc')
->findColumn('import_date')
->first();
but getting error:
Call to a member function first() on array
Any help or guidance is appreciated.
Suppose you have a model instantiated as
$userModel = new \App\Models\UserModel;
Now you can use it to get a query builder like.
$builder = $userModel->builder();
Use this builder to query anything for e.g.
$user = $builder->first();
Coming to your error.
return $this->orderBy('import_date', 'desc')
->findColumn('import_date');
findColumn always returns an array or null. So you can't use it as object. Instead you should do following.
return $this->orderBy('import_date', 'desc')->first();

Joomla: how to load JTable-element with LIKE-condition

I am using the following code to load a categorys record:
$res = JTable::getInstance('category');
$res->load(array('id' => $catid));
Now I would like to load the record based on its title which whould be matched against a SQL LIKE-pattern - is it possible to do this in a simple way with JTable, or do I need $dbo?
Far as I know JTable is made to be simple and carry only one element at a time, and through the primary key. If you really want something more advanced, I recomend that you use JDatabaseQuery way.
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all articles for users who have a username which starts with 'a'.
// Order it by the created date.
$query
->select(array('a.*', 'b.username', 'b.name'))
->from('#__content AS a')
->join('INNER', '#__users AS b ON (a.created_by = b.id)')
->where('b.username LIKE \'a%\'')
->order('a.created DESC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects.
$results = $db->loadObjectList();
In your case, instead of "$db->loadObjectList();" you can use "$db->loadObject();" for load just one item.
Source:
http://docs.joomla.org/Accessing_the_database_using_JDatabase/3.1

Returning one cell from Codeigniter Query

I want to query a table and only need one cell returned. Right now the only way I can think to do it is:
$query = $this->db->query('SELECT id FROM crops WHERE name = "wheat"');
if ($query->num_rows() > 0) {
$row = $query->row();
$crop_id = $row->id;
}
What I want is, since I'm select 'id' anyway, for that to be the result. IE: $query = 'cropId'.
Any ideas? Is this even possible?
Of course it's possible. Just use AND in your query:
$query = $this->db->query('SELECT id FROM crops WHERE name = "wheat" AND id = {$cropId}');
Or you could use the raw power of the provided Active Record class:
$this->db->select('id');
$this->db->from('crops');
$this->db->where('name','wheat');
$this->db->where('id',$cropId);
$query = $this->db->get();
If you just want the cropId from the whole column:
foreach ($query->result()->id as $cropId)
{
echo $cropId;
}
Try this out, I'm not sure if it will work:
$cropId = $query->first_row()->id;
Note that you want to swap your quotes around: use " for your PHP strings, and ' for your SQL strings. First of all, it would not be compatible with PostgreSQL and other database systems that check such things.
Otherwise, as Christopher told you, you can test the crop identifier in your query. Only if you define a string between '...' in PHP, the variables are not going to be replaced in the strings. So he showed the wrong PHP code.
"SELECT ... $somevar ..."
will work better.
Yet, there is a security issue in writing such strings: it is very dangerous because $somevar could represent some additional SQL and completely transform your SELECT in something that you do not even want to think about. Therefore, the Active Record as mentioned by Christopher is a lot safer.

PDO fetchColumn() and fetchObject() which is better and proper usage

It's been bugging me, I have a query which returns a single row and I need to get their corresponding column value.
//Retrieve Ticket Information to Database
$r = db_query("SELECT title, description, terms_cond, image, social_status, sched_stat FROM giveaway_table WHERE ticket_id = :ticket_id",
array(
':ticket_id' => $ticket_id
));
There are two ways that I can get data which is, by using fetchColumn() and fetchObject()
fetchObject()
$object = $r->fetchObject();
$ticket_info[] = $object->title;
$ticket_info[] = $object->description;
$ticket_info[] = $object->terms_cond;
$ticket_info[] = $object->image;
$ticket_info[] = $object->social_status;
$ticket_info[] = $object->sched_stat;
fetchColumn()
$title = $r->fetchColumn() //Returns title column value
$description = $r->fetchColumn(1) //Returns description column value
Was wondering, which one is better, or are there any pros and cons about this stuff?
if possible, can you guys also suggest the best way (if there's any) on how to retrieve all columns that's been selected in a query and store it into an array with less line of code.
There are two ways that I can get data which is, by using fetchColumn() and fetchObject()
really? what about fetch()?
There is a PDO tag wiki where you can find everything you need
I don't know pros and cons of using it. In my project I often used fetching as array rather than object. It was more comfortable. But if you make ORM projects then maybe it would be better to use fetchObject and make it your object not a std_class. You could make a contructor that has one parametr which is stdClass and make your object from this class
Answering your other question you can fetch all columns using fetchAll();
Follow this link to learn more about this function http://www.php.net/manual/en/pdostatement.fetchall.php
More about abstract database layer you can find here -> http://www.doctrine-project.org/

In yii how to access other tables fields

I am creating project in yii framework. I am having table as-
Qbquestion QbquestionOption
-questionId -optionId
-question -questionId
-userId -option
-isPublished -isAnswer
In QbquestionOption controller i want to access Qbquestion tables fields. I had written quesry as-
$Question=Qbquestion::model()->findAllByAttributes(array("questionId"=>$number));
where $number is some random number.
When i am using its fields as= $Question->isPublished then its giving error as "trying to get access to property of non-object"
Statement var_dump($Question) is showing all record and all values of Qbquestion table. So how can i access records?
Please help me
$Question is an array of models you cannot call model function on that..
what you can do is:
$questions = Qbquestion::model()->findAllByAttributes(array("questionId"=>$number));
foreach($questions as $question)
$question->isPublished()
or you can use findByAttribute to get single result..
findAllByAttributes returns an array of objects.
If you just want one question, use findByAttributes instead, then it should work as you want.
Try As I don't know your relation n all. Just give a try. I'll post other answers if it don't works. Also tel me in which table isPublished field is? If it in other table as your title mentioned you need to change it as echo $qRec->OtherTableRelationArrayKey->isPublished;
foreach($Question AS $qRec)
{
echo $qRec->isPublished;
echo "<br />";
}