CodeIgniter - Query array output three times instead one - php

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.'"');

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.

"in" property in Extbase for querying multi-values in TYPO3

The "in" property used in Extbase does not seem to be working for me.
$actor contains an array of Actor model objects. My Movie model and Actor are in m:n relation.
I tried something like this in my Movie Repository:
$query=$this->createQuery();
$query->matching($query->in('actors',$actors));
$result = $query->execute()->toArray();
$result is showing NULL
I tried passing array of actor uids too but that wont work as well:
$query->matching($query->in('actors',[$actor_1_uid,$actor_2_uid]));
There is of course contains but using in should be more convenient.
I don't see any problem in your statement. Just to be clear, a "in" statement must be placed somewhere inside a matching statement, which is correct in your case.
However, you should change your create query for
$query = $this->createQuery();
instead of
$query=$this->create->query();
If you have still no result, I suggest you check the exact the SQL statement executed by extbase, there's a tricky way to do it in TYPO3.
You have to locate the following file in the core:/typo3/sysext/extbase/Classes/Persistence/Generic/Storage/Typo3DbBackend.php
locate the replacePlaceHolders function and add the following codes at the end of the function:
if (strpos( $sqlString, "my_table_name" ) !== false) {
echo $sqlString;
}
I will echo every statement that is being made for the following "my_table_name" table. Of course, never do that in your production server.
I hope it will help!
Cheers,
Olivier
Sorry, but $query->in is the wrong approach. AFAIK it will not work for m:n reations, only for 1:n.
Try something like this, $actors being a query result from the model or the actors repository:
$constraints = array();
foreach ($actors as $actor) {
$constraints[] = $query->contains('actors', $actor->getUid());
}
if (!empty($constraints)) {
$result = $query->matching($query->logicalOr($constraints))->execute();
}
Of course you can use your own array of uids for the loop, then just drop the getUid() method

How do i call the function I created in my Model on the view

I just created this function in the model to see who im following in my social network... how do i call it in the view??
function isfollowing($following){
$user_id = $this->session->userdata('uid');
$this->db->select('*');
$this->db->from('membership');
$this->db->join('following', "membership.id = following.tofollow_id");
$this->db->where("tofollow_id","$following");
$this->db->where("user_id", "$user_id");
$q = $this->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
Now in my VIEW how do i call it being that i had already made a function to get the current logged on user's id and that is equal to $r->id
How do i call it here?? what goes after the "==" in that if statement?
THE VIEW
<?php if ( $r->id == ): ?>
It is not a good practice to call model function from view.
There are some alternatives about it. You can use anyone you like.
First
When you are loading a view call your model function and pass it in a variable
than this variable will be passed to view.
Controller
$following_status = $this->my_model->isfollowing($following);
$data['following_status'] = $following_status;
$this->load->view('my_view',$data);
View
<p>$following_status</p>
Secound
If you want to be independent of model you can create helper which you can
use anywhere in the application. You will have to create a CI instance to
get it working.
custom_helper.php
function isfollowing($following)
{
$CI = get_instance();
$user_id = $CI->session->userdata('uid');
$CI->db->select('*');
$CI->db->from('membership');
$CI->db->join('following', "membership.id = following.tofollow_id");
$CI->db->where("tofollow_id","$following");
$CI->db->where("user_id", "$user_id");
$q = $CI->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
View
//load the custom helper before using it (you can autoload of in autoload.php)
//or use common way $this->load->helper('custom');
<p>isfollowing($yourparameter)</p>
You do the following:
(1) Load your model in the controller that creates your page or auto load it
(2) In your view, type something like:
$this->The_custom_model->isfollowing($theinputvariable)
where The_custom_model is the model where you defined the isfollowing() function.
$theinputvariable is the appropriate argument value for your function. Keep in mind that you have specified an object as the argument to your function so you need to think about that.
this is an amended version to what raheel posted showing an if check - probably not necessary for your question, but to give you some things to think about...
// check to see if anything come back from the database?
if ( ! $data['following_status'] = $this->my_model->isfollowing($following) ) {
// nothing came back, jump to another method to deal with it
$this->noFollowers() ; }
// else we have a result, and its already set to data, so ready to go
else {
// do more here, call your view, etc
}
databases can go down even if the web page is working so its good to get in the habit of checking the results. the more error checks you can do in your controller and models, the cleaner your view files will be.
To access model into your view you first load it into autoload file like this
$autoload['model'] = array('model_name');
then in view you can get it by using this line of code
$this->model_name->isfollowing($following)
in isfollowing you will pass your tofollow_id

PHP MVC loop in the view

I consider myself as a php beginner, so it may be possible that this question is too easy for someone, but I got really confused on how to solve it. I am trying to loop something from the database in my views. So, in a quick way I solved it like this:
I've created a function in my model that does the loop and in the same time is creating the html and saves it in a variable. Then, I get that variable from my controller and I pass it in my view. But, it seems that this is not a good way to solve it, since if I want to change my html I need to enter my model function instead some of the view files.
Then, I've created another function in my model that looks like this:
function displayUsers() {
$sql = $this->pdo->prepare('select * from user');
$sql->execute();
while($row = $sql->fetch())
$results[] = $row;
return $results;
}
Now... I take the result in my controller, and send it in the view, but then... I don't know how to extract the results from my variable. I have done something like this:
while($output) {
foreach($output[$i] as $key => $value)
$data[$key] = $value;
echo $data['email'];
$i++;
}
But then, in the end it says to me undefined offset, which means I am referring to an array key that doesn't exist. Can anyone help me on how to solve this issue?
Proper MVC shouldn't have any output in the model or the controller.
Ideally you would have a model that just gets the raw data and returns it in the controller. The controller can then build up an array of values that we'll call data. For example:
Controller
$data['users'] = $this->MyModel->getusers(); // Getting the users from your model
$data['posts'] = $this->MyModel->getposts(); // Getting the posts from your model
$this->getTemplate('userdisplay', $data); // Get the template userdisplay and pass data
This gets the data from the model, and then assigns it to a key within the "data" variable. You can then pass the data variable into the template. You'll then have two variables to work with in the template, $users and $posts.
You'll need a "getTemplate" function that properly maps the data array to individual variables for use in the template, but all of the display should be located in the template.
To answer your specific question at the end, something like this should work in the template:
if (count($users) > 0) {
foreach ($users as $person) {
echo $person['email'];
}
}
You should be able to do this:
foreach($output as $row) {
echo $row['email'];
}

Making anchor load page containing data from referenced row in DB

I'm trying to learn the code igniter library and object oriented PHP in general and have a question.
I've gotten as far as making a page which loads all of the rows from my database and in there, I'm echoing an anchor tag which is a link to the following structure.
echo anchor("videos/video/$row->video_id", $row->video_title);
So, I have a class called Videos which extends the controller, within that class there is index and video, which is being called correctly (when you click on the video title, it sends you to videos/video/5 for example, 5 being the primary key of the table I'm working with.
So basically all I'm trying to do is pass that 5 back to the controller, and then have the particular video page output the particular rows data from the videos table. My function in my controller for video looks like this:
function video()
{
$data['main_content'] = 'video';
$data['video_title'] = 'test';
$this->load->view('includes/template', $data);
}
So ya, basically test should be instead of test, a returned value of a query which says get in the table "videos", the row with the video_id of "5", and make $data['video_title'] equal to value of video_title in database...
Should have this figured out by now but don't, any help would be appreciated!
I don't know if I'm too late but maybe this can solve your problem...
put this in your video() function
data[$query] = $this->db->query("SELECT * FROM videos WHERE video_id = 5");
and then that in your video_view file...
if ($query->num_rows() > 0)
{
$row = $query->row_array();
echo $row['title'];
echo $row['something'];
echo $row['somethingElse'];
}
this is a good resource: http://codeigniter.com/user_guide/database/index.html
hope that helps...
and please someone edit the question because it's too hard to read...
What you need is to understand how the URI Class works
Basically:
$default_url_args = array('video');
$url_args = $this->uri->uri_to_assoc(3,$default_url_args);
$video_UID = $url_args['video'];
and then something like
$the_video = $this->videos_model->get_video_by_UID($video_UID);
You could use the URI Class, or you can do the following:
function video($video_id)
{
$data['main_content'] = $this->videoprovider->get_video( $video_id );
$data['video_title'] = 'test';
$this->load->view('includes/template', $data);
}
In other words, with functions inside classes that extend Controller, you can add parameters to those functions and CI will automatically pass in the URI items in order to those parameters.
function generic_function_in_controller($item1, $item2, ...)
{
// would receive as: http://example.com/controller/generic_function_in_controller/item1/item2
}

Categories