Im getting the id from a form using
$id=$this->uri->segment(2)
I need your help to replace that by something else generic without getting the id from the url
im using pagination in several pages too & im using
$this->uri->segment()
too ..
PS:when i want to display a list o programs that belong to a category & when i want to display the list of programs of channel that belong to a category ,the segment change so i wont use the segment i wanna get the id dynamically ..
Best regards
Don't know if this is what you are after, but you can send parameters in a standard codeigniter install with URI and catch them in the method params.
class Welcome extends MY_Controller {
public function index($a = NULL, $b = NULL, $c= NULL)
{
echo 'Testing params: <br>
Param1: ' . $a . '<br>Param2: ' . $b . '<br>Param3: ' . $c;
}
}
Calling http://example.com/index.php/welcome/index/test1/test2/test3 will render
Testing params:
Param1: test1
Param2: test2
Param3: test3
Example
Going by this comment code:
foreach $rows as $row .. .. id; ?>"
href="program/details_program/id; ?>"> program_title; ?> page detail.php $id
= $this->uri->segment(2); $query = $this->db->get_where('programs', array('id' => $id));
it looks like you have a program controller with a details_program method that you are linking to and this is where you want a different solution to uri->segment. If this is the case, something like this would work with a URL like http://example.com/program/program_details/123:
class Program extends CI_Controller{
function program_details($id = NULL){
$query = $this->db->get_where('programs', array('id' => $id));
}
}
If this isn't what you want, please update the question with all of the relevant (properly formatted) code
Related
I have used a code from Internet to call controller action dynamically. Here is the code for that, and is used in web.php. But I dont fully understand what it does.
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Can someone explain?
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
The first line looks at the request to see whether it is a get or post request, if it is some other types of request that means it does not match and will not proceed further. Then the url are separated into 4 parts corresponding by their name and passed into variables with the same name i.e. $controller, $action, $param1 and $params2 where the last 3 variables do not need to be present (with ? at the end of the name).
$params = explode('/', $params1);
$params[1] = $params2;
I believe this is a crude way to create an array of parameters as $params where the following would be more appropriate.
$params = [$params1, $params2];
.
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
Then load the relevant controller.
return $controller->callAction($action, $params);
And run the corresponding action and passing all the parameters with it.
Hope this makes sense.
This is example of use it:
If you have controller like bellow:
class AdminController extends Controller {
public function index(){ //sample 0, sample 1
...
}
public function view($param1){ //sample2 , sample3
...
}
}
There is some sample route for calling them
sample0: yoursite.com/admin
sample1: yoursite.com/admin/index
sample2: yoursite.com/admin/view
sample3: yoursite.com/admin/view/5
Notice in your question ? in {action?} means it can either have value or not. Other things is simple and clear. Do you need more explaination?
I read a lot of forum topics but I did not found any answer which meets my needs.
I am running a blog system and my current urls for each article look like: www.example.com/controller/method/id. However, for each article I have a title stored in a database, and would like to use that title in the url, so it would look like this: www.example.com/title
Hello there you are asking for a whole lot of code and you did not do any research yourself.
The best way is to use id with your title: http://www.example.com/id/long-title it is much better than using only title, because:
same title can occur more than once (creates problem that can be avoided)
slow loading/searching due querying by slug instead of ID (slow performance)
user needs to remember whole title (with id+title; user can copy partially broken url www.example.com/234593/this-title-is-) / opinion based
In order to make my proposal work you need to:
set up routes (application/config/routes.php)
//leave two CodeIgniter's routes on top
$route['default_controller'] = "welcome";
$route['404_override'] = '';
//leave this two routes in this order + make them LAST routes
$route['(:num)'] = 'blog/post/$1'; //if only id is in url
$route['(:num)/(:any)'] = 'blog/post/$1/$2'; //if id and title is in url
set up controller (application/controllers/blog.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
//load models helpers etc if not autoloaded
$this->load->helper('url');
}
public function index()
{
echo 'should throw 404 or redirect home because id was not provided';
}
public function post($id = null, $title = '')
{
if (!$this->validId( $id )) redirect(); //redirect somewhere because id of post is invalid search/404/home...
if (empty(trim($title))) {
redirect(base_url().$id.'/'.$this->getTitle($id), 'location', 301); //redirect to same page search engines friendly (301 header)
}
//display what you need
echo 'params; id: ' . $id . ' title: ' . $title;
}
private function validId($id)
{
if (is_numeric($id))
return true; //use database to check validity in this case every id is valid
}
private function getTitle()
{
//id should be good to use at this point
//get title using database
return $this->seoUrl('How you react of crying babies will determine their future.'); //made up title
}
private function seoUrl($string)
{
//source: http://stackoverflow.com/a/11330527/1564365
//Lower case everything
$string = strtolower($string);
//Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
}
/* End of file blog.php */
/* Location: ./application/controllers/blog.php */
thats it, now create yourself model that can validate ID, grab title...
sample code (of model):
public function isInDb($table, $where = array())
{
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? true : false; //returns either true or false, pretty straight forward
}
public function getColumn(){}
Now you use (generate) url www.example.com/1 (this will redirect with 301 header to /1/title) or you can use (generate) www.example.com/1/title link, however if you generate url like: /1/fake-title (title is invalid for id 1 it will not redirect to the correct one)
This solution is SEO friendly.
Here is what their documentation says
You can also pass a string to result() which represents a class to
instantiate for each result object (note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user) {
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
Despite the fact that they are echoing $row instead of $user... this does not seem to work for me. Here is my version of testing it
Model
class User extends CI_Model{
var $first;
var $last;
..
function getName() {
return $this->first + " " + $this->last;
}
}
Controller
class Tester extends CI_Controller {
public function index() {
$this->load->model('User');
$query = $this->db->query('SELECT * from USERS');
$data = array (
'regular' => $query->result(),
'modeled' => $query->result('User')
);
$this->load->view('test', $data);
}
}
View
foreach ($regular as $row) {
echo "{$row->FIRST} {$row->LAST} <BR/>";
}
echo "<br/>";
foreach ($modeled as $row) {
echo "{$row->getName()} <BR/>";
}
Is there something that I'm doing wrong or misunderstanding? I would assume that based on their documentation, that if I assign a class to the result set, the class should be populated with the results? Now, how it goes on knowing which field to map to is a mystery to me and may very well be the reason why this doesn't work. I thought perhaps I needed to modify the constructor to do this mapping but I didn't see any documentation as to how I would go about doing that. I tried putting in a parameter for the constructor assuming it was an StdClass array but didn't seem to work.
Any clarifications would be great!
So it dawned on me to check the actual source code of the db_results function and I figured that it's due to the case of the query result columns. And it seems that CI defaults everything to UPPERCASE unless you specify it as lowercase in your query string.
So in conclusion, whatever the case of columns is in your query, should be the case of values in your Model!
Seems ridiculous though... I'll probably see if I can edit the core class to not be case-sensitive. Unless someone has better alternatives.
if i have to display some data from the database, how do i pass this data in the admin controller? Say i am defining a block in my controller
$block = $this->getLayout()->createBlock('core/text')->setText('<h1>Main Block</h1>');
Can i pass any sort of data to the setText() function to display the data i require in the admin page or are there other functions? I want to display a few order no from my custom table in the back end.
I tried something like this : $block = $this->getLayout()->createBlock('core/text')->setText('<h1>Main Block</h1><div>'.$this->showAllRecordsAction().'</div>');
The showAllRecordsAction() retrieves data from the custom table and displays it. When i try this out, i see the data at the top of the page and not in the content block.
How can i display it in a content block? Thanks.
I was able to get the content displayed through a block.
Used this code in my indexController :
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('adminhelloworld/view'))
->renderLayout();
This is my View.php in the Block/View.php
<?php
class Foostor_Adminhelloworld_Block_View extends Mage_Core_Block_Template
{
protected function _toHtml()
{
$html="";
$records = Mage::getModel('direcpay/database')->getCollection();
foreach($records as $db_record){
$html = $html . 'Order no : '.$db_record->getOrder_no().' Referecnce id : ';
$html = $html . $db_record->getDirecpay_refid()."<br/>";
}
return $html;
Hope this helps someone.
I have a controller with an index function as follows:
function index()
{
$this->load->model('products_model');
$data['product'] = $this->products_model->get(3); // 3 = product id
$data['product_no'] = 3;
$data['main_content'] = 'product_view';
//print_r($data['products']);
$this->load->view('includes/template', $data);
}
This is the get function in the products_model file
function get($id)
{
$results = $this->db->get_where('products', array('id' => $id))->result();
//get the first item
$result = $results[0];
return $result;
}
The products table contains fields such as name, price etc. Please can you tell me how to output variables from $data['product'] after it is passed into the view? I have tried so many things but nothing is working, even though the print_r (commented out) shows the data - it is not being passed into the view. I thought it may have been because the view calls a template file which references the main_content variable:
Template file contents:
<?php $this->load->view('includes/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer'); ?>
but i tried creating a flat view file and still couldn't access the variables.
Many thanks,
your $data array is "ripped" into single variables within the view.
print $product;
print $product_no;
print $main_content;
Handling headers & footers this way sucks and get's unmanageable pretty quickly.
Try using my Template library, your data will be passed through to the product_view no problem.