Generate multiple result in codeigniter - php

Currently I am working on one Web-based software which creates results automatically in codeigniter. I create modules like add student, add marks & generate mark sheet. here in generate marksheet i created individual marksheet but now I want to generate code for generate marksheet on one button click.
For that i use file_get_content(), curl(), fopen() but this all showing blank page if file_get_content("http://127.0.0.1/exam/admission/forms/showResult/41/2/1")
shows individual students result i want to show it in page
Here is My controller code
class forms extends CI_Controller {
function __construct() {
parent::__construct();
$this->admin_layout->setLayout('template/layout_admission');
$session = $this->session->userdata('admin_session');
if (empty($session) || $session->type != 'admission') {
$this->session->set_flashdata('error', 'Login First');
redirect(base_url() . 'login', 'refresh');
}
function printDoc(){
$siteaddressAPI = "http://127.0.0.1/exam/admission/forms/showResult/41/2/1";
$data = file_get_contents($siteaddressAPI);
echo $data;
}
}

Your Question does not explain exactly what you need.!!! Better you can give your sample code with expected result.
Still I have a solution which might help you in some way.
You can use view template to generate mark-sheet code. For Example:
$mark_sheets = array();
foreach($all_students_data as $student_data){
$mark_sheets[] = $this -> load -> view('marksheet_template', $student_data, TRUE);
}
Here $this -> load -> view() with third parameter TRUE will return generated html code and then store it in mark_sheets array.
By this way, you can access all your mark-sheets from $mark_sheets array.

Related

Codeigniter - anchor uri segment - creating a template file to load in dynamic data

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

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

How to get view as an object into an action helper

I have a custom Action Helper that is working fine.
It's generating a dynamic login box if user is not logged in, and if he is, it is generating a menu.
But here I have a problem.
I want to generate that menu from a small view that's called user_menu.phtml
How I can get that view into my view helper, and assign it to an object?
Ok, some update, sorry for being stupid, actualy I have Action Helper:
I'm sorry If I was specific enough while writing my initial question.
So I have a Action helper in: library/Hlp/Action/Helper
That helper renders a form, if user is not loged inn.
Here is my Helper method, that does that job:
public function preDispatch()
{
$view = $this->getView();
$identity = Zend_Auth::getInstance()->getIdentity();
$session = new Zend_Session_Namespace('users_session');
$user_id = $session->idd;
if( !empty($identity) ) {
$userModel = new Application_Model_Vartotojai();
$user_email = $userModel->geUserRowBy('id', $user_id);
$user_email = $user_email['email'];
$view->login_meniu = $identity.' -
[id:'.$user_id.']<br />['.$user_email.'] <br/>
Log OUt';
//here I would like to read view file to an object or some other variable
//if posible to an object si I would be able to inject some values
} else {
$form = new Application_Form_LoginForm();
$view->login_meniu = $form;
$view->register_link = '<br />Register';
//here I would like to read view file to an object or some other variable
//if posible to an object si I would be able to inject some values
}
Additionaly to that form I want to add some links, or other HTML content, that would br stored in a view file.
All you have to do is to extend the Zend_View_Helper_Abstract class. Then you have the view object stored in the public property $view.
By using that object you could render your file with
return $this->view->partial('user_menu.phtml');
Update
Since you've updated your question I will update my answer leaving the previous answer because it's still valid for your previous question.
In your case you already have the $view object, to do what you're asking for in the comments simply use the partial helper attached to the view in this way:
$renderedScript = $view->partial('user_menu.phtml',
array('id' => $user_id, 'email' => $user_email['email']));
By giving an array or an object as second argument to the partial call you can use them as model in your script file. Example:
// content of user_menu.phtml
<h1>Login info</h1>
<p>
[id: <?=$this->user_id?>]<br />
[<?=$this->email?>] <br/>
Log Out'
</p>
P.s. I've used the short_tags + the equal sign (=) shorthand for echo in the view script, if you are not using them you should replace with <?php echo $this->email ?>
From the view, you can pass the this to the helper
myHelper($this,$otherVars )
And then from the helper you can call the other helper
myHelper($view, $otherVars){
$view->otherHelper()
}

How to convert an existing PHP library file so it can be used in a CakePHP framework?

I have this library in PHP non-Cake format, the usual PHP scripting which currently works like a charm. I need to use this in a Cake framework. The library file is as follow: (example extracted)
<?php
// REST API functions
function sendAction($itemurl, $itemimageurl, $sessionid, $userid, $rating=""){
global $someapiwebsiteURL, $apiKey, $tenantId;
$somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.
.....
................
}
//Codes extract
?>
I've come across a few ways of doing it. Currently confused, how am I going to place this library file into my Cake framework?
App::import()
Datasource
The functions in the library file above (I supposed it'd be used in one of my Controllers to render the data outputting through the view).
Currently working in a non-Cake framework structure, the view page is such as: (example extracted)
<?php
// my view page
$viewResponse = sendAction($itemdescription ,$itemurl , $itemimageurl,$sessionid,$userid);
//sample code only
?>
Both the files are working fine. The logic of putting it in a CakePHP framework is the problem here. Anyone may suggest "the" way of doing this without over-strenuously working on a data source? If we have to use a data source in App/models/datasources/, how exactly is the structure of it? Like, e.g., in datasource file, do we include the library functions? or is it some generic ReST datasource file which can be found here: CakePHP ReST datasource . I've gone through the cookbook chapter on datasource and understand we have to define the datasource in our database.php, but if someone is certain about their way of accomplishing it either using datasource or app::import() method, please share with more details?
UPDATE:
Hi Lionel!, thanks for filling up. Well, actually users will click on view action: function view (){} in my foods_controller. I'm appending some scripts here to include my view function in my foods_controller so maybe it may help you to help out easier. Thanks..
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid food', true));
$this->redirect(array('action' => 'index'));
}
$this->set('food', $this->Food->read(null, $id));
}
The view action triggers the send_action function, (each time a user clicks on view page on foods controller). So each time, a user clicks on view action, his (dynamic variables): userid, sessionid, that page's itemid, url, itemdescription; (timerange value is a static string value "ALL"), and if any (etc.), so far only these values are available: Will be used as the "parameters" in the Send Action function. What you wrote is close to what the codes can do. You're right. Except we should include the Send Action function inside the view() in foods controller?
If we look at dynamically filling in the variables mentioned in the point above, could you modify your second code (the code from your product_controller, e.g.) so it also works to receive the variables dynamically? (as you asked in the last update: how to get the parameters..)
Just to make it clear.
A user views the page. The send action collects data and send to the API. (as we've already done by calling the function in the library the (ACME.php). *just waiting for your update if possible, thanks.
In the function view() of the foods controller: there's also an additional calling. The (2)second calling which is this:
$recommendResponse = getRecommendations("otherusersviewed", $itemId, $userId);
The second calling calls the ACME.php library file in which there consists the (2)second function that retrieves data, here it is: (it's in working order, but just needs to be changed into a public static function like you did for the (1)first function. Could you help to modify this code too, please?:
function getRecommendations($recommendationType, $itemId, $userId){
// sample code similar to the first one.
}
That's all to it. It seems quite simple in the normal PHP format, and it works easily, but getting it on an MVC framweork is a bit challenging for some, a lot for me. Thanks for helping out, Lionel. :-)
P.S. Hi Lionel, I notice something missing in the library after changes? Look originally we have this:
$somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.
Look, the variables for $SomeWebsiteAPI and $SomeApiWebsiteURL are different. Did I miss out something? or you have modified so it is more efficient ? I see that the variable named $SomeWebsiteAPI is modified to become variable called $link ? and variable $SomeApiWebsiteURL is changed to the named variable, $url, am I right ? .. thanks.
Thanks, best regards. John Maxim
To me, if I have this piece of code, I would first wrap it into a static (or normal) class, and named it ACME, then I will move the acme.php into /apps/libs/acme.php. Then in the controller, I will use App::import('Lib', 'acme'). This action do nothing but just requiring the file, so you can just use it instantly by calling ACME::sendAction(...).
And regarding the global thing, you might just need to declare a static (or normal) class, then define the shared variables as part of the class properties, so you can share them among all the functions in the class.
For example, this is the /app/libs/acme.php
class ACME {
private static $someapiwebsiteURL = "http://thewebsite/api/1.0/";
private static $apiKey = "0010KIUMLA0PLQA665JJ";
private static $tenantId = "THE_TENANT_NAME";
/**
* Simple builder to build links from array of $params
*
* #param string $url The api url
* #param array $params The given parameters
* #return string built url
*/
private static function BuildLink($url="", $params=array()) {
$link = $url;
foreach($params as $k=>$v) {
$link .= "&$k=$v";
}
//Replace the first & to ?
$link = preg_replace("/&/", "?", $link, 1);
//Not sure if we need URL encode here, please uncomment this
//if the API could not work.
//$link = urlencode($link);
return $link;
}
public static function SendAction($action, $itemId, $itemdescription, $itemurl, $itemimageurl, $sessionid, $userid, $rating="") {
$somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$action, array(
"apikey"=>self::$apiKey,
"sessionid"=>$sessionid,
"userid"=>$userid,
"tenantid"=>self::$tenantId,
"itemid"=>$itemId,
"itemdescription"=>$itemdescription,
"itemurl"=>$itemurl,
"itemimageurl"=>$itemimageurl,
/**
* Assuming your API smart enough to only use this value when
* the action is "rate"
*/
"ratingvalue"=>$rating
));
$xml = simplexml_load_file($somewebsiteAPI);
return $xml;
}
public static function GetRecommendations($recommendationType, $itemId, $userId) {
$somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$recommendationType, array(
'apikey'=>self::$apiKey,
'tenantid'=>self::$tenantId,
'itemid'=>$itemId,
'userid'=>$userId
));
$xml = simplexml_load_file($somewebsiteAPI);
return $xml;
}
}
And in your controller
App::import('Lib', 'acme');
class FoodController extends AppController {
//Food is plural already I assume? You can just use
//food, should be ok I think, else it will be weird
//to use /foods/view/?
var $name = "Food";
var $uses = array("Item", "Food");
function view($id="") {
//We accepts only valid $id and $id > 0.
//Take notes that this $id will be a string, not int.
if (ctype_digit($id) && $id > 0) {
//I don't know how you would gather the information, but I assume you
//have a database with the information ready.
//I assumed you have an `items` table
$item = $this->Item->findById($id);
$sessionid = "00988PPLO899223NHQQFA069F5434DB7EC2E34"; //$this->Session->...?
$timeRange = "ALL";
$userid = "24EH1725550099LLAOP3"; //$this->Auth->user('id')?
if (!empty($item)) {
$desc = $item['Item']['description'];
$url = "/foods/view/".$id;
$img = $item['Item']['img'];
$viewResponse = ACME::SendAction("view", $id, $desc ,$url, $img, $sessionid, $userid);
$this->set('food', $this->Food->read(null, $id));
}else{
$this->Session->setFlash(__('Invalid food', true));
$this->redirect(array('action' => 'index'));
}
}else{
$this->Session->setFlash(__('Invalid food', true));
$this->redirect(array('action' => 'index'));
}
}
}
Edit
The code has been filled up, and of course, without any warranty :). I personally don't really like to have long arguments in a function (like SendAction, error prune), rather use shorter one like the $params in ACME::BuildLink. But just to respect your code, I didn't modify much on the SendAction method.
Then I'm not too sure how you would make use of this code, so I assumed you have a ProductsController, and somehow the user trigger url like /products/send_action/. If you can provide more information, then we would be able to help out.
Edit Again
I have modified the ACME class, as well as the controller. Yea I do miss out some variables, but I had added them back to the updated code.
Not too sure if it would work (perhaps typo), you can just modify the code if it doesn't work for you.
And for personal conventions, I usually capitalize methods which are static, like ACME:GetRecommendations or ACME::SendAction.
Oh yea, I better stick back to the variables you used. Sorry for modifying them, just I don't like long names :)
And btw, the RoadRunner's ACME Corporation? Lol!
Cheers
Lionel

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