Adding additional data to select query result - php

I am fetching data from Articles table but I want to extend returned result with some data from another table.
For example:
public function getArticlesByCategoryId($category_id = 0) {
$select = $this->_db->select()
->from($this->_name)
->limit(5)
->order("pubDate DESC");
$result = $this->_db->fetchAll($select);
$mCategories = new Model_Categories();
foreach($result as $row) { // as &$row doesn't work
$category_name = $mCategories->getNameById($row["category_id"]);
$row["category_name"] = $category_name; // this to add to $result but dunno how
// blah blah...
}
return $result; // the new one with ...->category_name in it.
}
I hope you could understand what I am looking for.
Or maybe it is better to write a single query (with joins, don't know how) and fetch all the data needed in once without calling methods from another Models?

This indeed looks like you should use a join. This definitely is the easiest way to solve your problem. The following query would do the trick:
$select = $this->_db->select()
->from($this->_name)
->join('category_table', 'category_table.id = ' . $this->_name . '.category_id', array('category_name'))
->limit(5)
->order("pubDate DESC");
This will add the category name to the row.
In case you don't want to use a join, you can add a custom field to your row by using a custom row class. This however requires a bit more work. Create the class as follows:
class MyApp_Model_Row_MyRow extends Zend_Db_Table_Row_Abstract
{
public $categoryName;
}
Then you should indicate in your DbTable class that you want to use this new row class:
class MyApp_Model_DbTable_Articles extends Zend_Db_Table_Abstract
{
...
protected $_rowClass = 'MyApp_Model_Row_MyRow';
}
You can then set the category name in a fetched row.

To get all articles with data from your category table your query could look like:
$select = $this->_db->select()
->from($this->_name)
->joinLeftUsing('category','category_id', array('category_name'))
->order("pubDate DESC");
See also: http://framework.zend.com/manual/en/zend.db.select.html

Related

Making where clause dynamic in sql in CI

I want to display the content of page dynamically this following code is working fine but it only shows the content of specific id...how can i make that dynamic??
Model
public function getAllDepartment() {
$join = $this->db->query( "Select * from labreport_db inner join patient_db on labreport_db.P_ID=patient_db.id where labreport_db.P_ID=15");
return $join->result_array();
}
Controller
public function reportDisplay(){
$data['clubs'] = $this->labdoc_model->getAllDepartment();
$this->load->view('SystemAdminUser/labreport', $data);
}
There is simple work around for this using Query Builder class of CI.
So this is how your code will look like,
$id=15;
$this->db->select('*');
$this->db->from('labreport_db');
$this->db->join('patient_db', 'labreport_db.P_ID = patient_db.id');
$this->db->where('labreport_db.P_ID', $id);
$query = $this->db->get();
This is standard approach in CI to make database operation using query builder class in which you can perform dynamic WHERE condition.
For which just change the value of $id and the query will do the needful.
Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#selecting-data
Hold the id in some variable like:
$pid = $_REQUEST['p_id'];
// $_REQUEST['p_id'] will contain the dynamic value in it
and put this variable in your query like:
where labreport_db.P_ID = $pid;
It will show the data for the value contained in $pid, and make sure it contains the dynamic value in it.
You can used this code for you solution.
Model.php
public function getAllDepartment($pId) {
$join = $this->db->query( "Select * from labreport_db inner join patient_db on labreport_db.P_ID=patient_db.id where labreport_db.P_ID=".$pId);
return $join->result_array();
}
Controller.php
public function reportDisplay(){
$pid = $_REQUEST['pid']; //OR $_GET['pid']; OR $_POST['pid']; You can pass your id for get content
$data['clubs'] = $this->labdoc_model->getAllDepartment($pid);
$this->load->view('SystemAdminUser/labreport', $data);
}
There are a couple of ways doing it. One of them is through CI routing ability.
Model
public function getAllDepartment($p_id = 0) {
$join = $this->db->query( "Select * from labreport_db inner join patient_db on labreport_db.P_ID=patient_db.id where labreport_db.P_ID={$p_id}");
return $join->result_array();
}
Comment: I added $p_id as a variable to fetch the ID dynamically.
Controller
public function reportDisplay($p_id = 0){
$data['clubs'] = $this->labdoc_model->getAllDepartment($p_id);
$this->load->view('SystemAdminUser/labreport', $data);
}
Comment: We also add a variable called $p_id in the reportDisplay function and pass it to your model's getAllDepartment()function.
How to fetch the report dynamically
I don't know your URL structure, but for example purposes let's say it's http://localhost/yourcontrollername/reportDisplay/
To access it dynamically, simply add an ID after the reportDisplay
For example:
http://localhost/yourcontrollername/reportDisplay/15
http://localhost/yourcontrollername/reportDisplay/10

Sort alphabetically when multiple queries?

I am having difficulty sorting my data results alphabetically when matching them with the User that has placed the item in their "Locker".
I have two queries; the first one searches the database for all of the items that the user placed in their 'locker', and the second query pulls the details of the item and sorts them into a list by which brand the items are.
I feel like there is a better way to do this rather than forcing the page to run the query once for each item, but am not sure the proper way to write out the mySQL in the most efficient way that works.
I think the solution would be to pull all IDs as an array, then somehow search and sort all of their associated brands in the second query.
I currently have:
//$lockerid is pulled earlier in the code based on which locker number is associated with this user
// Pull all of the items and their ids that are in this users locker
$userlockerquery= mysql_query("SELECT DISTINCT item_id FROM lockers WHERE user_id = '$profile_userid' AND locker_id ='$lockerid' ");
while($lockeritems=mysql_fetch_array($userlockerquery)){
$indi_item=$lockeritems[item_id];
$lockeritemdetails = mysql_query("SELECT DISTINCT brand FROM inventory WHERE id = '$indi_item' ");
$brands=mysql_fetch_array($lockeritemdetails );
$brandname=$brands[brand];
echo '<div>'.$brandname.'</div>';
}
Although the results do show up with all of the brands, My problem seems to be that since the query is ran once for each items id, it cannot have the list results talk to each other, and thus cannot have them ordered by ASC alphabetically, since the query is ran once per each item.
Also because of this, the DISTINCT flag does not have any effect, since it is not matching against any other results.
As an example, my results would return in divs in order of ID instead of brand, and repeating:
Nike
Puma
Puma
Converse
Rather than
Converse
Nike
Puma
Adding the ORDER BY flag to the second query did not help, so I figured I would try to ask here for some ideas. Please let me know if any other details are needed!
Maybe try something like this class. See if it will work for your needs. It's hard to check it without trying the sql queries, but provided I've written it properly, it should work.
class MyLocker
{
// Protected means that you can't use this variable outside of the functions/class
// so you can not use $myLocker->_array; It will throw an error
protected $_array;
// Construct is basically used as an auto-function. It will execute automatically
// when you create a new instance of the class so as soon as you do this:
// $myLocker = new MyLocker($_locker); you initiate the __construct
// When you label as public, you allow it to be used outside of itself
public function __construct($_array)
{
// When you set this variable, it is now open to use in all
// other functions in this class.
$this->_array = $_array;
}
// This is the method that will do everything
public function LockerContents()
{
// Loop through query. Since the $_array was set in the __construct
// it is available in this function as $this->_array
while($lockeritems = mysql_fetch_array($this->_array)){
// $brand is something we want to use in other functions but not
// outside the class so it is set here for use in the Fetch() function
$this->brand = $lockeritems['item_id'];
// We ant to use our Fetch() function to return our brand
$_brand = $this->Fetch();
// If brand available, set it to an array
if(!empty($_brand))
$array[] = $_brand;
}
if(isset($array)) {
// Sort the array
asort($array);
// Finally, we use the Display() function for the final output
$this->Display($array);
}
else { ?>
<div>Locker is empty.</div><?php
}
}
// Establish this as an in-class variable
protected $brand;
// Establish this as a public function incase we want to use it by itself
// To do so you would write $myLocker->Fetch(); outside of the class.
// Since you need $brand for this function to work, you would need to turn
// $brand from "protected" to "public" and write $myLocker->brand = 'whatever';
// before you run the $myLocker->Fetch();
public function Fetch()
{
$query = mysql_query("SELECT DISTINCT brand FROM inventory WHERE id = '".$this->brand."'");
$brands = mysql_fetch_array($query);
// Return brand
return (isset($brands['brand']))? $brands['brand']:"";
}
protected function Display($array)
{
if(is_array($array)) {
foreach($array as $object) { ?>
<div><?php echo $object; ?></div><?php
}
}
}
}
// You should be using mysqli_ or PDO for your db connections/functions.
$_locker = mysql_query("SELECT DISTINCT item_id FROM lockers WHERE user_id = '$profile_userid' AND locker_id ='$lockerid' ");
// If there are more than 0 rows, create locker.
if(mysql_num_rows($_locker) > 0) {
// Create new instance of the locker app
$myLocker = new MyLocker($_locker);
// Display the results
$myLocker->LockerContents();
}

Custommize get column from findAll function Yii

I have some problem that, I am using criteria to customize a number column query
$criteria=new CDbCriteria();
$criteria->select =array('CompanyName', 'CompanyCountCoupon','CompanyDes', 'CompanyLogo');
$models = Company::model()->findAll($criteria);
After I put it to array and echo result
$rows = array();
foreach($models as $i=>$model1) {
$rows[$i] = $model1->attributes;
}
echo CJSON::encode($rows)
My problem is that the results contains all attributes of table, and attributes not in criteria->select will set = null
{"CompanyName":"abc","CompanyCountCoupon":"0","CompanyDes":"Hello","CompanyLogo":"\/upload\/company\/abc.jpg",**"CompanyID":null,"CompanyWebSite":null,"CompanyAdrress1":null,"CompanyAdrress2":null,"CompanyPhone1":null,"CompanyPhone2":null**}
Please help me.
Thanks to all
if you go with findAll() (using ActiveRecord) you won't be able to control that part, the way to go is a custom query :
$results = Yii::app()->db->createCommand()
->select('CompanyName ,CompanyCountCoupon ,CompanyDes ,CompanyLogo')
->from('company')
//->where() // where part
->queryAll();
echo CJSON::encode($results);
now its already good to be JSON encoded and also much faster than regular ActiveRecord
Use getAttributes()
Example
$rows = Company::model()->getAttributes(array('CompanyName','CompanyCountCoupon','CompanyDes', 'CompanyLogo'));
echo CJSON::encode($rows);
This is correct behaviour.
You are asking for specific columns, so this is being correctly provided.
Recall that the attributes is part of the model, not the query.
$model = Company::model()->findByPK();
print_r($model);
...
/* Company points to the TABLE. not the query */
class Company extends CActiveRecord
{
---
}

Fetch data from database issue

i have one issue i make a component and i add data add component data table that i want to fetch that data in my site how to do and i have one other issue how to put query in view.html.php file in components i have code i add my code i have one error i add my error
500 - View class not found [class, file]: team_memberViewteam_member, C:\wamp\www\Joomla_2.5.8-Stable-Full_Package\components\com_team_member\views\team_member\view.html.php
this is my code please help me how to fetch data in database....
// import Joomla view library
jimport('joomla.application.component.view');
/**
* HTML View class for the HelloWorld Component
*/
class HelloWorldViewHelloWorld extends JView
{
// Overwriting JView display method
function display($tpl = null)
{
// Assign data to the view
$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(array('id', 'member_name', 'member_pic', 'member_des','member_description'));
$query->from('#__gztqw_team_member_datadetails');
$query->where('profile_key LIKE \'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.
$results = $db->loadObjectList();
// Display the view
parent::display($tpl);
}
}
try simple way:-
$db = JFactory::getDbo();
$query = 'SELECT data FROM #__gztqw_team_member_datadetails WHERE profile_key LIKE "custom.%" order by ASC';
$db->setQuery($query);
$results = $db->loadObjectList();
also you have not returened any value in function and where you have display it the best way to show data in view use controllers function and assign result value to display in view
you need to read http://docs.joomla.org/Developing_a_Model-View-Controller_%28MVC%29_Component_for_Joomla!2.5
First of all, the class in your view is called HelloWorldViewHelloWorld, it should be called Team_memberViewTeam_member, this is what is causing your error.
Secondly, You should ideally put your database query into your model, however it will still work if you put it in your view. I have given you an example of how to make it work with the query in the view.
I have created a protected variable called $items, and assigned the results from the database to the variable.
In your template, you would then access the data from the database using
foreach($this->items as $item):
echo $item->id;
endforeach();
In your view you should have
class Team_memberViewTeam_member extends JView
{
protected $items;
// Overwriting JView display method
public function display($tpl = null)
{
$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(array('id', 'member_name', 'member_pic','member_des','member_description'));
$query->from('#__gztqw_team_member_datadetails');
$query->where('profile_key LIKE \'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.
$this->items = $db->loadObjectList();
parent::display($tpl);
}
}

Magento: select from database

I am working on my first module for magento version 1.3.2.3.
I have created a simple table (not EAV, just a primary key and 2 columns) and some classes to access it, following Alan Storm's articles which helped me a lot, but I can't figure out how to make a simple select: Alan explains how to load with the primary key, but not selecting rows that match some value.
In normal MySQL I'd write:
SELECT *
FROM my_table
WHERE some_field = '" . $someValue . "'
I've found a snippet which gives me the result I want:
$resource = new Mage_Core_Model_Resource();
$read = $resource->getConnection('core_read');
$select = $read->select()
->from('my_table')
->where('some_field = ?', $someValue);
return $read->fetchAll($select);
But there have to be an easier/prettier solution, using the model class I've created. The result will be a single row, not a collection.
I've tried everything I could think of, like:
return Mage::getModel('modulename/classname')->select()->where('some_field = ?', $comeValue);
return Mage::getModel('modulename/classname')->load()->where('some_field = ?', $comeValue);
return Mage::getModel('modulename/classname')->load(array('some_field = ?', $comeValue));
and more stuff, but no luck so far: what am I missing??
You probably want to use your model's Collection for that.
$collection = Mage::getModel('mygroup/mymodel')->getCollection();
$collection->addFieldToFilter('some_field',$some_value);
foreach($collection as $item)
{
var_dump($item);
}
var_dump($collection->getFirstItem());
var_dump($collection->getLastItem());
Here's an example of how this is achieved in the CoreUrlRewrite Model class:
public function loadByIdPath($path)
{
$this->setId(null)->load($path, 'id_path');
return $this;
}
You can create similar methods in your model classes. You can also use the alternative form of the load method anywhere in your code:
$model = Mage::getModel('modulename/classname')->load($someValue, 'some_field');

Categories