create custom url in codeiginter - php

i want show my products name in url
now i get my product with id and my url display like that.
www.mydomain.com/home/single/1
i want to show my product url with product name Like.
www.mydomain.com/home/single/New-Dell-Laptop
Here is my code that's get post with it's id number.
Controller
//get all products
public function index()
{
$data['products'] = $this->front->get_products();
$this->load->view('index',$data);
}
//get single product
public function single($id)
{
$data['product']=$this->front->get_product($id);
$this->load->view('product',$data);
}
Model
//get all products
public function get_products()
{
$this->db->select()
->from('vendor_products')
->where('DESC','date_added');
$data = $this->db->get();
return $data->result_array();
}
//get single product
public function get_product($id)
{
$this->db->select()
->from('vendor_products')
->where('prod_id',$id);
$data = $this->db->get();
return $data->first_row('array');
}
Views
//show all products index.php
<?php foreach($products as $one) : ?>
//create link for single product
<a href="<?=base_url();?>home/single/<?=$one['prod_id'];?>">
<?=$one['product_name'];?>
</a>
<p><?=$one['product_price'];?></p>
//show single product (product.php)
<p><?=$product['product_name'];?></p>
<p><?=$product['product_price'];?></p>
<p><?=$product['product_description'];?></p>

The string you`re humanizing, will be in a field, right?
www.mydomain.com/home/single/New-Dell-Laptop
So, if you select in database for "New Dell Laptop"
It will return 1 record, right? If so, you can configure something like this on Routes in config.
$route['single/{product}'] = 'productController/{product}';
Then when you load productController/New-Dell-Laptop
You can use $this->uri->segment(3) to get the value, and search in Database, retrieve page, and show to user.
You should use something like this:
www.mydomain.com/home/single/34/New-Dell-Laptop
Where 34 will be the id to the page and will be easy to you locate on database, but you should not get troubles to find if you search for "New Dell Laptop"

You can use routes.
In your config/routes.php
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->get('vendor_products');
$result = $query->result();
foreach( $result as $row )
{
$route["home/single/" . $row->product_name] = "home/single/" . $row->prod_id;
}
And then in your view, change
<a href="<?=base_url();?>home/single/<?=$one['prod_id'];?>">`
by
<a href="<?=base_url();?>home/single/<?=$one['product_name'];?>">`

Related

CodeIgniter global settings database

I am trying to implement global settings to each controller and views.
Having database table named config containing
config_name | config_value
title | My Website
email | my#example.com
In my model I have query:
function config()
{
$query = $this->db
->select('*')
->get('config');
return $query->result();
}
In controller I call model data this way
$data['cfg'] = $this->config_model->config();
Now I want to display certain bits of config in view by using
<title><?php echo $cfg->title; ?></title>
But I get an error Trying to get property of non-object
I tried result query options in model query:
result();
result_array();
But it won't work. What am I doing wrong?
try this in your model:
public function config() {
$q = $this->db->get('config')
return $q->result_array();
And this in your controller:
$this->load->model("config_model");
$res = $this->config_model->get();
if($res){
$data['result'] = $res;
$this->load->view('Your view here', $data);
} else {
echo "failed";
}
And then you can access like this in your view:
$result[0]['title'];
Assuming your config table only has one row.
Ok I have simplified things and solved it this way:
Changed database table layout to 1 row
title | email | country | city
And now it works. Previously i wanted db layout different, but i'll go with this now.
can be used like that
your model:
public function get() {
$query = $this->db->get('config');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[$row->item] = $row->val;
}
return $data;
}
return false;
}
use in the controller:
$this->load->model("config_model");
$config = $this->config_model->get();
echo $config['title'];
use in view:
$this->load->view('index',$config);
result:
<p><?=$title?></p>

How to reroute to another view when a resource doesn't exist in a table (Laravel 4)

I have a resource:
Route::resource('artists', 'ArtistsController');
For a particular url (domain.com/artists/{$id} or domain.com/artists/{$url_tag}), I can look at the individual page for a resource in the table artists. It is controlled by this function:
public function show($id)
{
if(!is_numeric($id)) {
$results = DB::select('select * from artists where url_tag = ?', array($id));
if(isset($results[0]->id) && !empty($results[0]->id)) {
$id = $results[0]->id;
}
}
else {
$artist = Artist::find($id);
}
$artist = Artist::find($id);
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}
What I would like to do is have all urls that are visited where the {$id} or the {$url_tag} don't exist int he table, to be rerouted to another page. For instance, if I typed domain.com/artists/jujubeee, and jujubee doesn't exist in the table in the $url_tag column, I want it rerouted to another page.
Any ideas on how to do this?
Thank you.
In your show method you may use something like this:
public function show($id)
{
$artist = Artist::find($id);
if($artist) {
return View::make('artists.show', compact('artist'))->with(...)
}
else {
return View::make('errors.notfound')->withID($id);
}
}
In your views folder create a folder named errors (if not present) and in this folder create a view named notfound.blade.php and in this view file you'll get the $id so you may show something useful with/without the id.
Alternatively, you may register a global NotFoundHttpException exception handler in your app/start/global.php file like this:
App::error(function(Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// Use $e->getMessage() to get the message from the object
return View::make('errors.notfound')->with('exception', $e);
});
To redirect to another page have a look at the redirect methods available on the responses page of the Laravel docs.
This is how I would go about doing it and note that you can also simplify your database queries using Eloquent:
public function show($id)
{
if( ! is_numeric($id)) {
// Select only the first result.
$artist = Arist::where('url_tag', $id)->first();
}
else {
// Select by primary key
$artist = Artist::find($id);
}
// If no artist was found
if( ! $artist) {
// Redirect to a different page.
return Redirect::to('path/to/user/not/found');
}
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}

Dealing with url request in CodeIgniter

I just started learning codeigniter and i must say its pretty easy but I have a problem dealing with wrong urls, for example:
if I have an anchor tag like this
http://example.com/info/2
in the controller if I have
public function info( $x ) {
$data['body'] = "Personal_info";
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
the controller grabs the links
segment (3)
and then grab the details of the id from the database.
now for instance if a user manually edit the link on the browser and change the
segment(3)
to lets say 7 and there is no id in the database as 4.
how do I handle such a problem? I am a beginner so please pardon me
You could use empty method to check if there is data and if not redirect away from the page.
public function info( $x )
{
$details = $this->person_model->get_detail( $x );
if(empty($details))
redirect('other/url');
$data['body'] = "Personal_info";
$data['details'] = details;
$this->load->view('view', $data);
}
This way it doesn't throw errors and potentially attempt to display something that doesn't exist.
you can check if the passed id exists in database before trying to fetch related data, like:
$data_exists = $this->person_model->data_exists( $x );
if( $data_exists ) {
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
else {
//load some view for showing no such id exists in db
}
where data_exists() can be a function in model which returns TRUE or FALSE depending on existance of your id in database.

Sending $data Variable From Model To View

Okay, so I have this snippet of code in a controller. However, it's all DB driven and should really be in model - I get that. However, as you can see in the IF statement, I need to pass along $data to my view. Based on the outcome. I tried pasting this chuck of coding in a method in my model (calling the model method via controller), however the $data[update_prompt] string is not getting called by the view...
How would I translate this code into a model - sending the $data values back to my controller to embed in my view?
// show appropriate upgrade message if user has free account
$id = $this->session->userdata('user_id');
$this->db->select('subscription'); // select the subscription column
$this->db->where('id', $id); //find id in table that matches session id
$query = $this->db->get("subscriptions"); // connect to this database
$subscribe = $query->result_array(); //returns the result of the above
if($subscribe[0]['subscription'] == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
You would add a function in your model, like so:
public function myModelFunction($id) {
//we return row as we are looking up by primary key and are guaranteed only one row
return $this->db->select('subscription')
->where('id', $id)
->get('subscriptions')
->row();
}
Then, in your controller:
public function myControllerFunction() {
$subscribe = $this->my_model->myModelFunction($this->session->userdata('id'));
if($subscribe->subscription == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
}

How to display total comments

Whatsup codeigniters!
I want to display total comments of my blog that I am building with codeigniter.
In my controller I have:
function index() {
$data['query'] = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);
}
Function index() gets all posts.
and I have
public function post($id) {
$data['query'] = $this->blog_model->get_post($id);
$data['comments'] = $this->blog_model->get_post_comment($id);
$data['post_id'] = $id;
$data['total_comments'] = $this->blog_model->total_comments($id);
$this->load->view('blog/index',$data,TRUE);
$this->load->helper('form');
$this->load->library(array('form_validation','session'));
//validation rules for post function
$this->form_validation->set_rules('commentor','Name','required');
$this->form_validation->set_rules('email','Your email','required|valid_email');
$this->form_validation->set_rules('comment','Comment','required');
if($this->blog_model->get_post($id))
{
foreach($this->blog_model->get_post($id) as $row)
{
//set page title
$data['title'] = $row->entry_name;
}
if($this->form_validation->run() == FALSE)
{
//if validation runs FALSE
$this->load->view('blog/post',$data);
}
else
{
//if valid
$name = $this->input->post('commentor');
$email = strtolower($this->input->post('email'));
$comment = $this->input->post('comment');
$post_id = $id;
$this->blog_model->add_new_comment($post_id,$name,$email,$comment);
$this->session->set_flashdata('message', '1 new comment added!');
redirect('blog/post/'.$id);
}
}
else
show_404();
}
Basically, post($id) gets a post with id (single post) and display comments. I can print total comments number in single post. But how do i print total comments number in index() function where all posts are listed. Thank you!
Use this active record
$this->db->select("post_id , count(comment) as total_comments");
$this->db->group_by('post_id');
$query = $this->db->get('comments');
This generate this sql query
SELECT
post_id,
count(comment) as total_comments
FROM comments
GROUP BY post_id
Means this selects posts , count of posts for each comment and seperate them by post. For understanding Here is the table Structure
Comments
id count(comment) post_id
Now the query will first fetch all the comments then it will use group by to seperate posts giving you total comments for each post.
Try to do something like this
in Model
public function fetch_all_comment()
{
$query = $this->db->get('comments');
return $query->result();
}
In Controller
$data['all_comments'] = $this->model_name->fetch_all_comment();
$this->load->view('viewname',$data);
In View
For this you have to call model in your view. for example if you want to display post name.
Load Model in view
foreach ($all_comments as $row)
{
echo $row->post;
echo $total_no_post = $this->model_name->fetch_total_no_of_comment_in_post($row->postid);
}
Count no of comment in this function fetch_total_no_of_comment_in_post

Categories