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
}
Related
I have a strange issue in Codeigniter. I have a controller and a model to fetch product listings from MySQL. I'm using the uri-segment functions to fetch the ID and put it into the model to retrieve that specific product listing based on the ID.
The right URl would be (which works great):
http://example.com/listing/2000
However, when you type:
http://example.com/listing/2000ddd
this also works, which it shouldn't.
On the other hand, if you try to type a charachter before the id-number, it doesn't work.
http://example.com/listing/ddd2000
My controller:
public function index()
{
$listing_id = $this->uri->segment(3);
$messageinfo = $this->Messages_model->get_messageinfo($listing_id);
$data["messageinfo"] = $messageinfo;
$this->load->view('inc_includes/header');
$this->load->view('pages_sendmessage/sendmessage', $data);
$this->load->view('inc_includes/footer');
}
My model:
function get_messageinfo($listing_id = NULL)
{
$this->db->select('
azzo.listing_ads.listing_ads_id,
azzo.listing_ads.listing_ads_domain_url,
azzo.listing_ads.listing_ads_expire,
azzo.listing_ads.listing_ads_user_id,
azzo.users.username,
azzo.listing_ads.listing_ads_outprice
');
$this->db->from('azzo.listing_ads');
$this->db->join('azzo.users', 'azzo.listing_ads.listing_ads_user_id = azzo.users.id', 'inner');
$this->db->where('azzo.listing_ads.listing_ads_id', $listing_id);
$query = $this->db->get();
if($query->num_rows() == NULL)
{
return false;
}
else
{
return $query->row();
}
}
Any suggestions? What am I doing wrong here?
The reason behind your problem is - your data($listing_id) is converted to integer type when used in model. When you pass 2000ddd as parameter, you will get 2000, but when you pass ddd2000, you will get 0.
Yep, what #Jobayer said... That's PHP performing type casting behind the scenes... So it's taking a guess by how it's being used which in this case, is an integer.
Just be aware that when you allow data entry via a URL or by any user input, it is open to folks trying out all sorts of things. You could test that the segment is meant to be an integer by using is_integer($expected_integer_variable_to_check) and take the appropriate action like even just ignoring it...
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.
I am currently making a static site into a dynamic one and have been using codeigniter to do this without any problem .. until now.
The problem I have is that I want to have one view (webpage) that acts as a template file and pulls in dynamic data from my database depending on what link was clicked.
In the website there is a overview jobs page where it has a sidebar that lists all current vacancies. What I want is when a user clicks on one of these links it will load the template file and pull in all the data (job description, job title etc) that relates to that job.
I don't think that I am to far away from achieving this but I am having some problems.
First I have created a function in the controller(site) which loads a model and function (getJobInfo) that gets the job title from the database (depending on the location). Then it gets the header, nav, content and pulls of of it into the view named "jobs".
In the jobs overview page I have used a foreach statement to load in the job title which will be used as the link to click on, here it will then load the template file with all the related data. In this foreach statement I have used a codeigniter anchor statement to load a new function (job position) back in the controller, this will be used to display and get all of the job specific information. I have also passed in the jobs listing id as the third segment of the anchor which will be used by a new model in the new site controller function (job position) where it will only show the related information to that id (where query).
If that makes no sence hopfully this will clarify.
Controller - job overview function
public function jobs(){
$this->load->model("get_db");
$data['jobheader'] = $this->get_db->getJobHeader('3');
$data['joblocationlisting'] = $this->get_db->getJobLocationListing('manchester');
$data['header'] = $this->get_db->getHeaders('3');
$data['content'] = $this->get_db->getContent('2');
$this->load->view("header", $data);
$this->load->view("nav");
$this->load->view("jobs", $data);
}
Model - get job title
public function getJobLocationListing($job_location){
$query = $this->db->query("SELECT job_location, job_listing_id, job_title
FROM job_location INNER JOIN job_listing ON job_location.job_location_id =
job_listing.job_location_id WHERE job_location = '$job_location'" );
return $query->result();
}
View - jobs
<ul>
<?php foreach($joblocationlisting as $row)
{
$title = $row->job_title;
?>
<li>
<?php
echo anchor("site/jobPosition/$row->job_listing_id", $title);
?>
</li>
<?php
}
?>
</ul>
Controller - job position function
public function jobPosition(){
$this->load->model("get_db");
$data['jobposition'] = $this->get_db->getJobInfo();
$this->load->view("header", $data);
$this->load->view("nav");
this->load->view("jobTemplate", $data);
}
Model - get job info
public function getJobInfo(){
$query = $this->db->where('job_listing_id', $this->uri->segment(3));
$this->db->get('job_listing');
return $query->result();
}
View - job position - template
<?php foreach($jobposition as $row)
{
$jobtitle = $row->job_title;
$jobdescription = $row->job_description;
}
?>
h1><?php echo $jobtitle; ?></h1>
<p><?php echo $jobdescription; ?></p>
The problem I have is that the anchor tag is loading the function - site/jobPosition(and the id number) e.g site/jobPosition/1. What I want is to load for the anchor to run the function site/jobPosition but it to pass the job_listing_id into the function which will then pass it to the getJobInfo model. Here it will which will get the data depending on that id cliked and then it will return it back to the jobPosition function for it to be displayed into the jobTemplate view.
Am I far away from doing this because I think I'm pretty close as have followed this tutorial video - http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-5-crud/ - and it works for him with deleted data instead of selecting and displaying it.
Thanks (sorry for the massive post).
Uhm, I franky had a bit of difficulties understanding the problem, so bear with me if I'm wrong:
So far you're fetching the job_listing_id using the uri segment
$query = $this->db->where('job_listing_id', $this->uri->segment(3));
You're already creating (with the anchor() method) the correct url, so why then in your controller you ignore the argument passed, and rely on the uri segment to fetch it? Why not doing:
public function jobPosition($job_listing_id){
$this->load->model("get_db");
$data['jobposition'] = $this->get_db->getJobInfo($job_listing_id);
$this->load->view("header", $data);
$this->load->view("nav");
this->load->view("jobTemplate", $data);
}
Model - get job info
public function getJobInfo($job_listing_id){
$query = $this->db->where('job_listing_id', $job_listing_id);
$this->db->get('job_listing');
return $query->result();
}
When you pass additional segments in the url they're automatically passed down to the controller method as arguments, so a url like yours,
echo anchor("site/jobPosition/$row->job_listing_id", $title);
will automatically hand the jobPosition() controller an argument, which is likely what you want.
EDIT
Maybe I get it. Try changing routes:
// Put this after the default routes:
$route['jobPosition/(:num)'] = "jobPosition/jobPosition/$1";
Now make sure your controller jobposition.php has the class jobPosition and the method jobPosition($job_listing_id) I posted up here. I used "jobPosition" for the method name for simplicity, change it accordingly to what you prefer: the router will pick up the URL that matches your rule ($route['jobPosition/(:num)']) and forward the request to any controller/method/argument you define
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.'"');
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