Codeigniter route page using value fetch from database - codeigniter

currently I have a page like the following -
abc.com/controller/action/23
Here 23 is Item id,which is dynamic. I have to fetch the name of the item using the id from database and route to a new url like following -
abc.com/controller/p/23-itemname.
How can I do that?

what you can do is when the user visits this page:
abc.com/controller/action/23
You put this code into the controller
CONTROLLER
function action()
{
$id = $this->uri->segment(3); //id is now 23, this is the third uri
$data['details'] = $this->YOUR_MODEL->get_details($id);
foreach($data['details'] as $d)
{
$itemname = $d->YOUR_TABLE_COLUMN_NAME;
}
redirect(base_url(). 'controller/p/' . $id . '-' . $itemname);
//line produces abc.com/controller/p/23-itemname
}
MODEL
function get_details($id)
{
$this->db->select('*');
$this->db->from('YOUR_TABLE_NAME');
$this->db->where('YOUR_ID_COLUMN_NAME',$id);
$query = $this->db->get();
return $query->result();
}
Just comment if you need more clarifications.
Goodluck meyt
EDIT
Since you have action and you redirect to function p, here is what will happen.
function p()
{
$explodethis = $this->uri->segment(3); //Contains "23-itemname"
$pieces = explode("-", $explodethis); //Separate by the dash
$id = $pieces[0]; //Contains "23"
$itemname = $pieces[1]; //Contains "itemname"
$data['details'] = $this->YOUR_MODEL->YOUR_FUNCTION(YOUR_PARAMETERS)
$this->load->view('YOUR_VIEW',$data);
}

Routing not required to do this. You may generate link by item name
<a href="<?php echo site_url('controller/action').'/'.$val['item_id'].'-'.$val['item_name']; ?>"
and now in controller explode this title to get ID of the item and then execute your query
$title = explode('-','23-item-name');
$id = trim($title[0]);//this is your item ID

Related

joomla - router change url when getting the name of product

I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)

Codeigniter pagination links dosnt work after the first page

i have a search field and i want to show the results with pagination.
every thing works well in first result page but in other pages there is noting to show without any errors and when back to first page also there is noting.
i putted the posted key in session to avoid losing it.
but still noting.
this is my controller:
public function search()
{
$this->session->set_userdata('searched',$this->input->post('searchterm'));
$searchterm = $this->session->userdata('searched');
$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
$config['base_url'] = base_url() . 'home/search';
$config['total_rows'] = $this->home_model->search_record_count($searchterm,$language);
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['display_pages'] = TRUE;
$choice = $config['total_rows']/$config['per_page'];
$config['num_links'] = 3;
$this->pagination->initialize($config);
$data['results'] = $this->home_model->search($searchterm,$limit,$language);
$data['links'] = $this->pagination->create_links();
$data['searchterm'] = $searchterm;
$data['total']= $this->home_model->search_record_count($searchterm,$language);
putHeader();
putTop();
putTopmenu();
putSearch($data);
putFooter();
}
this is my model:
public function search_record_count($searchterm)
{
$sql = "SELECT COUNT(*) As cnt FROM content WHERE body LIKE '%" . $searchterm . "%'";
$q = $this->db->query($sql);
$row = $q->row();
return $row->cnt;
}
public function search($searchterm,$limit)
{
$data = $this->db
->select('content.title,content.id,content.category,content.body,path')
->from('content')
->join('categories','noor_content.category = categories.id')
->like('noor_content.title', $searchterm)
->like('noor_content.body', $searchterm)
->limit("5")
->order_by("content.id","DESC")
->get();
if($data->num_rows() > 0)
{
return $data->result();
//print_r($data);exit();
}
else
{
return 0;
}
}
The problem is that you are not limiting your query according to the pagination. In your controller you are getting the 3rd URL segment
$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
And passing it to you model but then you are not doing anything with it. In your model you want to do something like
$data = $this->db
->select('content.title,content.id,content.category,content.body,path')
->from('content')
->join('categories','noor_content.category = categories.id')
->like('noor_content.title', $searchterm)
->like('noor_content.body', $searchterm)
->limit("10, " . $limit) //Edited this line
->order_by("content.id","DESC")
->get();
i think you should use method = 'get' instead of post... i mean some thing like this ..
<form method="get" action="your_controller/your_function">
//your search form
</form>
by using get instead of post u dont have to use any session variables and u can easily access them in your controller as
$this->input->get('feild_name');
moreover u wont have problem with second page or any other page in pagination as all the search feilds get attached in the url and u can access it easily using $this->input->get('feild_name'); untill your url is changes to something else.. i will aslo save u al ot of coding ..

accessing data linked by foreign key in site view of custom component

In my custom component, in site view, I have a list of countries (view: countries). Clicking on a country, another view is displayed (view: persons) showing all persons living in that country.
Now, in persons view, I want to display the country's name and flag.
So I want to add a function getCountry() in ...site/models/persons.php:
public function getCountry() {
$db = $this->getDBO();
$id = $this->state->get("filter.country");
$sql = "SELECT * FROM #__cnlp_persons_country WHERE id = $id";
$db->setQuery($sql);
$country = $db->loadResult();
// var_dump($country);
return $country;
}
Then, I added to .../site/views/persons/view.html.php:
class Cnlp_personsViewPersons extends JView
{
protected $items;
protected $state;
protected $params;
protected $country; // <--- I added this
...
public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->params = $app->getParams('com_cnlp_trainers');
$this->country = $this->get('Country'); // <--- I added this
(...)
Result: I thought I could then in ---/site/views/persons/tmpl/default.php something like...
<h1><?php echo $this->country->name; ?></h1>
<img src="<?php echo $this->country->flag; ?>" />
...but I get no output...
What did I do wrong?
$db->loadResult(); is used to load a single value results (for example if you would only want to select the country name or something like this), but in your query you're selecting an entire row, so you should use one of theese:
$db->loadRow(); // returns an indexed array from a single record in the table
$db->loadAssoc(); // returns an associated array from a single record in the table
$db->loadObject(); // returns a PHP object from a single record in the table:
You can read more about this here (it's joomla 1.5 documentation, but it's same for 2.5 and 3)

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Having Problem with $_get in Codeigniter

I have a page called list.php which retrieves from database and shows all the student names with their respective ids in a list. In raw php, this is how I have done this-
include("connect.php");
$query = "SELECT * FROM marks ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
mysql_close();
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$studentname = mysql_result($result,$i,"studentname");
$studentid = mysql_result($result,$i,"studentid");
?>
And then---
<? echo $studentname ?>
<?
++$i; } } else { echo "No Record Found"; }
?>
When a user clicks on any of the student names, it takes the user to the page of that particular student and in that page I have a code like following-
include("connect.php");
$number = $_GET['studentid'];
$qP = "SELECT * FROM student WHERE studentid = '$number' ";
$rsP = mysql_query($qP);
$row = mysql_fetch_array($rsP);
extract($row);
$studentid = trim($studentid);
$studentname = trim($studentname);
$studentgender = trim($studentgender);
The above code is working just fine. Now as far as I know $_get is disable in Codeigniter. But how to do the exact same thing that I mentioned above in codeigniter if $_get is disabled ? I went through some tutorials on alternative way of using $_get, but I didn't understand those well. Would you please kindly help? Thanks in Advance :)
The usage of $_GET is discouraged in CI.
The simpliest way to rewrite that files is not using $_GET. Just add method='post' to your forms and tell your ajax requests to use post, if you have any. Use $_POST in PHP instead of $_GET.
If you are absolutely sure you need get requests passing parameters, you have to enable query strings. You can do it in your CI's config file:
$config['enable_query_strings'] = TRUE;
See section 'Enabling query strings' for details. But enabling query strings will cause Url helper and other helpers that generate URLs to malfunction.
So my suggestion is to use POST requests.
UPDATE Replace
<? echo $studentname ?>
With
<? echo $studentname ?>
Create method studentprofile:
<?php
class Yourcontroller extends CI_Controller {
public function studentprofile($id)
{
include("connect.php");
$number = $id;
$qP = "SELECT * FROM student WHERE studentid = '$number' ";
$rsP = mysql_query($qP);
$row = mysql_fetch_array($rsP);
extract($row);
$studentid = trim($studentid);
$studentname = trim($studentname);
$studentgender = trim($studentgender);
// and so on...
}
}
?>

Resources