Fetch data from database issue - php

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);
}
}

Related

Getting data from database to model

So far I've used many objects in my applications but often if I had to for example display for example users' profiles on page I simply got 20 users from database as array using some method in my object and assigned it to view.
Now I want to create application more with models that represent real data. So for each user I should probably have User object with properties .
Here I put sample code to get users from database and to display them in PHP:
<?php
$db = new mysqli('localhost', 'root', '', 'mytest');
class User
{
private $id;
private $name;
public function __construct($data)
{
foreach ($data as $k => $v) {
if (property_exists($this, $k)) {
$this->$k = $v;
}
}
}
public function show()
{
return $this->id . ' ' . $this->name ;
}
}
$result = $db->query("SELECT * FROM `user` LIMIT 20");
$users = array();
while ($data = $result->fetch_object()) {
$data->x = 10; // just to test if property isn't created
$users[] = new User($data);
}
// displaying it on page
foreach ($users as $user) {
echo $user->show() . "<br />";
}
Questions:
Is it the way I should use data from database into model? I mean if should I create object for each record even if the only role of this object would be returning some data to view (for example even not modified by any functions as in this example). Of course I know that often data should be prepared to display or made some calculations or additional data should be retrieved from database before those data could be used to display.
Is there any way to assign object properties from database simpler than using constructor with loop?
First of all, i'd move the DB operations in a separate class, not inline with the User class. You could create an abstract Model class, which the User class would extend and add DB logic to it.
You'd have a select() method to query the database, which would return an array of objects of the class that extended the Model class (the User class in this case).
To answer your questions:
I think it's ok. Most ORMs work this way.
An alternative would be to assign the user row data from the DB to a $data attribute in your User class and use the magic methods __get and __set to access them.

Magento Controller shows all the rows from table

As I am required to pirnt the ratings of products in JSON format, i have made a module with controller and rating.php file in model folder. We I run the controller it shows all the data from that table, But I required only a single row. So through the url i am passing a parameter, but it wont works. I am attaching my indexcontroller.php here. suggest me upon this.
<?php
class Modulename_CustomRating_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction ()
{
$arrParams = $this->getRequest()->getParams();
var_dump($arrParams);
$collection = Mage::getModel('Modulename_CustomRating_Model_CustomRating')->getCollection();
}
print_r (json_encode($collection ->getData()));
}
}
?>
As I am passing url as:localhost/magento/customrating?vote_id=1 , it is taking the parameter to it but returns whole table's data. I know this is due to getData(); but how to make to get the required row?
You have to use setEntityPkFilter method. Check Mage_Rating_Model_Resource_Rating_Option_Vote_Collection class for other methods.
$product_id = $this->getRequest()->getParam('product_id'); // or 'vote_id'
$collection = Mage::getModel('Modulename_CustomRating_Model_CustomRating')
->getResourceCollection()
->setEntityPkFilter($product_id);
If you want only 1 column you can try some Zend stuff because you can't use addAttributeToSelect. getSelect() returns Zend like query:
$adapter = $this->getConnection(); // $this->getConnection();
$collection->getSelect()
->reset(Zend_Db_Select::COLUMNS) // remove all columns
->columns('attribute_name'); // add only needed one
$result = $adapter->fetchAll($select);
Not sure whether this would work. It's not tested, just an idea.

Adding additional data to select query result

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

How do you create a settings function in codeigniter?

I have created a MY_Controller and I'm linking to it through my main controller... I am now trying to create a settings function which will get all the results from a database and return the one you want... The only problem I'm having is being able to do using the template engine...
protected function settings()
{
// select all settings from database
$query = $this->db->query('SELECT * FROM settings');
// get result from database
$this->data['settings'] = $query->result_array();
// return array of data
return $this->data['settings'];
}
How can i go about this?
The only way I can access it at the moment is:
{settings}
{name}
{value}
{/settings}
P.S. I call the function $this->settings() in the __construct() function also I forgot to mention I'm using codeigniter
Controller code:
$data['settings'] = $this->settings();
$this->load->view('whatever_your_view_file_is_named', $data);
Now in your view the setting properties will be available as members of an object named settings as that was the key you set in the data array you pass to the view.
View code:
echo $settings->name;

PHP MVC in Joomla Component

Im working on a pre created joomla component which using the MVC Architecture, My problem like this:
In Models i have a .php file with database fetch function as
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.model' );
class class_name extends JModel
{
var $_data;
function getlast_year(){
$query = 'SELECT year FROM `table` ORDER BY year DESC LIMIT 0,1';
$this->_db->setQuery( $query );
return $this->_db->loadResult();
}
}
I added a new function to the same class file: (I have updated the table columns too in MVC /tables)
as:
function getAttendenceData()
{
$query="SELECT id,octSec,octNin,octSect,octSec,octTwent FROM `table`";
$this->_db->setQuery( $query );
//$this->_data = $this->_db->loadObjectList();
$this->_data = $this->_db->loadObject();
return $this->_db->loadObjectList();
}
but in view i cant still access the fetched data from the above new function but older functions are working property
This is not an actual answer but response to the comment.
First in your view.html.php file, you'll have to retrieve data from the model.
$attendance_data = & $this->get('AttendenceData');
This'll give you the object list as you are returning from your getAttendenceData() function.
Now assign it to a view variable (lets say data).
$this->assignRef('data', $attendance_data);
Now you can access this data in your view:
foreach($data as $r)
{
echo $r->id;
}
Isn't the problem that you are attempting to fetch the data twice?
With this line you retrieve it and store it locally in the class's _data variable.
$this->_data = $this->_db->loadObject();
With this line you attempt to retrieve the data again but you've already retrieved it (if there was only one result). You therefore are probably returning a false
return $this->_db->loadObjectList();
You should probably return $this->_data at the end of the function - assuming the original function you are copying was indeed functional.

Categories