How to send value as parameter to model in codeigniter to get data? - codeigniter

I am new in codeigniter.
Currently working in e-commerce site I want to send the category_id as parameter to bring product data.
I want to know the steps to detail and Thanks
This is my model:
( function get_category(){ $query = $this->db->query("SELECT a.category_id,a.category_name from ci_intro.categories a order by a.category_id"); return $query->result(); } function get_product($id){ $q = $this->db->query('select * from products where category_id = $id'); if($q->num_rows() > 0){ foreach ($q->result() as $row) { $data[] = $row; } return $data; } } )
and this is my controller
( public function services() { $this->load->model("get_db"); $data['results'] = $this->get_db->get_category(); $id=$this->input->post('id'); $data['cat_id'] = $this->get_db->get_product($id); $this->load->view("view_header"); $this->load->view("view_nav"); $this->load->view("content_portfolio",$data); $this->load->view("site_footer"); } )

You get category_id in model as $_GET['category_id'] or $_REQUEST['category_id'] in model also .

class Pages extends CI_Controller {
public function view($page = 'home')
{
$this->load->model('services_model');
$id=$this->input->post('id');
$data['records']= $this->services_model->getData($id);
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
this is your controller example
and this is mlodel for you
class Services_model extends CI_Model {
function getUser($id) {
$q = $this->db->query('YOUR QUERY HERE');
if($q->num_rows() > 0){
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
}
you can see various crud example and their website for further details

Your category should be the drop downlist. on change event the id will be pass through ajax like below
$(document).ready(function() {
$("#category").change(function(){
/*dropdown post */
$.ajax({
url:"<?php echo base_url(); ?>index.php/services/getproducts",
data: {catid: $(this).val()},
type: "POST",
success: function(data){
$("#product").html(data);
}
});
});
}
get prducts will be the function in services controller class you can get the category id using the
$this->input->post('catid');

Related

Codeigniter: Display an image stored in DB

How do I get an image stored in a field of my database, and put it into a variable for using it in an email message like a signature?
Here is my code:
//Model user_model
function getImage(){
$this->db->select("image");
$this->db->where("$id", user_id);
$query = $this->db->get("users");
if($query->num_rows()>0){
return result();
}else{
return false;
}
}
//Controller user_controller
function image(){
this->load->model("user_model");
$id = $this->session->userdata('id');
$image = $this->user_model->getImage($id);
echo $image;
}
Here is a example
Model user_model
// Pass the id function
function getImage($id){
$this->db->where($id, 'user_id');
$query = $this->db->get("users");
if($query->num_rows()>0){
return $query->row_array();
}else{
return false;
}
}
Controller user_controller
function image(){
$this->load->model("user_model");
$somedata = $this->user_model->getImage($this->session->userdata('id'));
$data['image'] = $somedata['image'];
$this->load->view('someview', $data);
}
On view
<?php echo $image;?>

maintain url in codeigniter for pages,categories,subcategories and product?

I'm trying to do URL format likes below
for pages -
www.example.com/page-name
for categories
www.example.com/category-name/sub-category-name
for product
www.example.com/category-name/sub-category-name/product-name
This should not be a problem if you are using only one controller i.e. your default controller. Say your default controller is called "Home". Then you can simply do this.
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Home_model');
}
public function _remap()
{
$category = $this->uri->segment(2);
$sub_category = $this->uri->segment(3);
$product = $this->uri->segment(4);
// Check what you have
// echo $category.'_'. $sub_category.'_'. $product;
if($category == '' || $sub_category == '' || $product == '')
{
//send user to landing page of website
$this->load->view('landing');
}
else
{
// get the product details
$render['product_details] = $this->Home_model->get_product_details($category, $sub_category, $product);
// send product details to view
$this->load->view('product_details', $render);
}
}
}

Codeigniter database check

i am currently working on a project where users can save note snippets in there own little user area.
I was wondering how would i check if the id of an item exists for example if a user visits
http://mysite.com/view/1 and there is a note snippet of 1 it will display all the data relating to the id of one. Now if the user was to change the url to lets say 1000, that id doesnt exist and the view just errors.
i want to be able to redirect them back to a certain page with a error message "snippet does not exist" etc.
heres what i have so far ( i currently already have a conditional statement in here to check if the snippet is private, then if it is redirect back to /publicsnippets)
Controller:
class Publicsnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['public_snippets'] = $this->dashboard_model->public_snippets();
$this->load->view('dashboard/public_snippets', $this->data);
}
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}
}
Model:
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
public function delete_snippet($snippet_id)
{
$this->db->where('id', $snippet_id);
$this->db->delete('snippets');
}
}
View:
<h3>Description</h3>
<p><?php echo $snippet['description']; ?></p>
<h3>Tags</h3>
<p><?php echo $snippet['tags']; ?></p>
<h3>Date Submitted</h3>
<p><?php echo $snippet['date_submitted']; ?></p>
<h3>Snippet</h3></pre>
<pre class="prettyprint"><?php echo $snippet['code_snippet']; ?></pre>
You work is fine just add a check like this in your view method
Controller
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if($snippet){
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}else{
$this->session->set_flashdata('message', "<b style=\"color:red;\">snippet does not exist</b>");
redirect('/publicsnippets');
}
}
if no row is found in get_snippet method the $snippet will contain false or null
and the second block of condition will run.
In your model change get_snippet() to check for rows:
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
Then in your controller:
if ($snippet = $this->dashboard_model->get_snippet($snippet_id)) {
// code if snippet exists
} else {
// code if snippet doesn't exist
}
OR
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet) {
// etc...

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

CodeIgniter: How to pass variables to a model while loading

In CI, I have a model...
<?php
class User_crud extends CI_Model {
var $base_url;
var $category;
var $brand;
var $filter;
var $limit;
var $page_number;
public function __construct($category, $brand, $filter, $limit, $page_number) {
$this->base_url = base_url();
$this->category = $category;
$this->brand = $brand;
$this->filter = $filter;
$this->limit = $limit;
$this->page_number = $page_number;
}
public function get_categories() {
// output
$output = "";
// query
$this->db->select("name");
$this->db->from("categories");
$query = $this->db->get();
// zero
if ($query->num_rows() < 1) {
$output .= "No results found";
return $output;
}
// result
$output .= "<li><a class=\"name\">Categories</a></li>\n";
foreach ($query->result_array as $row) {
$output = "<li>{$row['name']}</li>\n";
}
return $output;
}
while I am calling this in my controller...
<?php
class Pages extends CI_Controller {
// home page
public function home() {
}
// products page
public function products($category = "cell phones", $brand = "all", $filter = "latest") {
// loading
$this->load->model("user_crud");
//
}
Now, How can I pass the $category, $brand and $filter variables to the user_crud model while loading/instantiation?
You shouldn't be using your model like this, just pass the items you need for the functions you require:
$this->load->model("user_crud");
$data['categories'] = $this->user_crud->get_categories($id, $category, $etc);
I would suggest (after seeing your code) that you study the fantastic codeigniter userguide as it has really good examples, and you just went a totally different way (treating model like an object). Its more simple sticking to how it was designed vs what you are doing.
You can not. A better idea would be to setup some setters in your model class along with some private vars and set them after loading the model.
if you return $this from the setters you can even chain them together like $this->your_model->set_var1('test')->set_var2('test2');

Resources