Welcome Guest, Not a member yet? Register   Sign In
Query Bindings with a variable
#1

[eluser]epseix[/eluser]
OK, last question for today (promise).

I have the following controller:

Code:
<?php
class Work extends CI_Controller {

    public function show($strId)
    {
  $this->load->model('Width_model');
  $data['query'] = $this->Width_model->get_tq();
  $this->load->view('head_view', $data);
  $this->load->view('body_header_view', $data);
  $this->load->view('body_fullwidth_view', $data);
  $this->load->view('body_footer_view', $data);
    }
}

As the $strId in the controller (and URL) is a variable, I had wanted to use it in the model query bindings to look up a certain record from my database - but error message tells me $strId is undefined.

Code:
<?php
class Width_model extends CI_Model{

    function __construct(){
        // Call the Model constructor
        parent::__construct();
    }

    function get_tq(){
  $sql = "SELECT * FROM myDb WHERE strId = ?";
  $query = $this->db->query($sql, array($strId));
  return $query->result();
    }
}

Any advice?

Cheers! Smile
#2

[eluser]jairoh_[/eluser]
there's no problem in query bindings or any other way like active records or doctrine.
the problem is just because u didn't passed the parameter $srtId.

in your controller should be
Code:
$data['query'] = $this->Width_model->get_tq( $strId );

and your model function should be
Code:
function get_tq( $strId ){
    blah blah blah
}
#3

[eluser]boltsabre[/eluser]
As per jairoh_, you have not passed the variable from your controller to your model.

One thing to consider, instead of defining $strId as a variable of your controller method show(), and then passing it to your model you can simply access it direct in your model using $this->uri->segment(2) like this:

Code:
//your model
function get_tq(){
  $sql = "SELECT * FROM myDb WHERE strId = ?";
  $query = $this->db->query($sql, array($this->uri->segment(2)));
  return $query->result();
}

This save code, and reduced the chances of bugs. Also, I'd suggest you also do some data cleansing on your variable first, if someone changes this variable (I'm assuming it should be a int) to a string your db query will fail. If someone removes it from the url it will fail.

I personally like to check 1. that is is set, 2. that it in an int. If either fail I just throw a custom 404 error. This ensure that it has not been tampered with and can prevent any nasty SEO things from bots crawling pages that should not exist, thus reducing "duplicate content" and "low quality" pages from being indexed!!! Trust me, it can happen and hurt your rankings!

Then I also check that the result actually returned something. If it didn't I throw a 404 http response in my view and show the user a nice little "This what-ever does no seem to exist in our database, it's possible it has been deleted. Here are your options" type of message.




Theme © iAndrew 2016 - Forum software by © MyBB