Codeigniter mysql query - php

I have my model set like this, so that it gets all the data from the table "tests" in the previously specified database:
<?php class Get_db extends CI_Model {
public function getData()
{
$query = $this->db->get("tests");
return $query->result();
}}?>
and after I loaded all this data in my controller, and passed it to my view, I got this function in my view:
<?php
foreach ($records as $rec) {
echo $rec->id." ".$rec->name." ";
?>
and all the ids and names in my database will be posted where i want.
But what if I wanted to be more selective. Let's say that I've got a param. in my db called "color" some of my rows will have color set to (for example) red, and some others to blue.
How can I display in my view just the rows with color=red?
Or, more exacty, how can I tell php to get the data just of the rows that have color=red?

CodeIgniter uses an ActiveRecord library, be sure to read the documentation as it is clearly stated there.
You can use $this->db->get_where() to filter on a WHERE clause. In your case:
$query = $this->db->get_where('tests', array('color' => 'red'));

Related

How to handle result objects from MySQL

I am trying to get some relational database handling to work, using PHP and MySQL. To combine output from two different tables, I found some help here on stackoverflow. On of the suggestions was to combine the output in one result object (as I understand it), so the code looks like this:
// Function to read all projects from database
public function get_projects() {
$query = "SELECT pt.*, at.* FROM ed_projects as pt, ed_project_address as at WHERE pt.project_id = at.project_id";
$db_result = $this->db->query($query);
$result_object = $db_result->result();
return $result_object;
}
Where ed_project is the name of the main table, and ed_project_address is the subtable (or whatever it is called), which contains streetname, postal code, city, etc. for each project. The address properties are linked to projects by a project_id.
I can get this to work on the "reading from the database" part, but when I try to use it, I get an error: "Fatal error: Cannot use object of type stdClass as array in (...)". As I am using CodeIgniter, it is passed through 2 additional steps:
Project View Controller:
/* index() - Project view controller
* Handles the showing of the project main page, that is the list of all
* projects found in the database. See also views/projects/index.php.
*/
public function index() {
$data['projects'] = $this->project_model->get_projects();
$data['title'] = 'Ejendomme';
$this->load->view('templates/header', $data);
$this->load->view('projects/index', $data);
$this->load->view('templates/footer');
}
Project View:
<?php foreach ($projects as $projects_item): ?>
<h2><?php echo $projects_item['pt.projects']->project_name ?></h2>
<div class="main"><?php echo $projects_item['at.address_street'] ?></div>
<?php endforeach ?>
The error is in Project View (index.php) on line 3. I have been reading quite a bit on objects in PHP, but the addition of the CodeIgniter framework seems to obscure things just enough for me to not get it :-(. Am I way off here? Or am I just missing the very last bit?
you just made mistake
at your model you returns the object
return $result_object;
but you using it as array at view.
you should use it like this
$projects_item->project_name
If you want to use it as array at your view you should return data from model like this
$result_object = $db_result->result_array();
Also your query will produce error if your both table has same column name. In that case you have to specify which column form which table you want to select.

CodeIgniter - Query array output three times instead one

Output is wrong , i Got three the same comment instead only one.
Can anyone help to make only one comment.
Here my view php code:
$modelid = "5" ;
$query = $this->db->query('SELECT message FROM message WHERE modelid = '.$modelid.' ');
$row = $query->row();
echo $row->message;
and my Table:
http://dev.interactive-creation-works.net/Stack/table.png
The controller:
class Comment extends CI_Controller
{
function index()
{
$data['result'] = $this->db->get('message')->result();
$this->load->view('commentView',$data);
}
function insert()
{
$this->load->model('commentjquery');
echo $this->commentjquery->inserttodb();
}
}
This view should only show one message, even if you do - for whatever reason, correctly or not - get three messages from the query. You may be loading the view three times in your controller. Try adding some static text to the top and bottom of your view, and see if it shows up multiple times.
Edit:
Now that you've posted the controller, I can see that's not the issue. But I notice you're trying to grab the comments from the database twice - once in the controller and once in the model. The one in the controller is actually the wrong way to do it unless you've implemented an ActiveRecord model for your comments, and you're not using the results anyway.
Another thing I noticed just now is that you're calling $query->row() instead of running a foreach over $query->result(). Try this:
foreach($query->result() as $row) {
echo $row->message;
}
Edit 2: Or maybe it is the problem, if the code snippet you posted isn't the entire view, which seems to be the case.
It's really weird that you aren't getting error. It gets weirder when you get three outputs.
Change your query to this.
$query = $this->db->query('SELECT message FROM message WHERE modelid = "'.$modelid.'"');

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.

How to query a database from view - CodeIgniter

I have query that runs in the controller:
$data['query'] = $this->Member->select_sql($id);
$this->load->view('myform');
and then outputs data in the view:
foreach ($query->result() as $row):
echo $row->post_title;
echo $row->post_user_id;
endforeach;
So this outputs me a list of posts made by a user. Now I would like to run one more query that would for each post loop through my user table and output user information next to each post. (I dont want to select data from a view or joint those 2 tables at this time in MySQL)
Any ideas?
Although it is not a good practice, the "cleanest" approach would be as follows:
Grab the CI instance in the View
Load the model containing your desired data extraction query functions
Run the function from the model in the view
So, in the view:
$CI =& get_instance();
$CI->load->model('modelname');
$result = $CI->modelname->functionname();
var_dump($result);
Tested and working.
Inject the database adapter or appropriate table object into the View.
From your code above, I'd assume this would be
$data['userModel'] = $this->User;
Then use it from there to run your query, e.g.
$user = $userModel->select_sql($row->post_user_id);
Simply
<?php
$qryd='select * from '.$tbname.'';
$queryd = $this->db->query($qryd);
$resultset = $queryd->result_array();
?>

CodeIgniter get_where

I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.

Categories