1

I am having problems in fetching data from my database here is my getOne function

public function getOne($sku)
{
    $ans = 0;
    $query = $this->db->query('SELECT * FROM barcode_sku WHERE sku = "$sku"');
    $res = $query->result();
    $row = $res[0];
    $ans =  $row->quantity;
    
    
    return $ans;
}

the variable $sku will have values like bc_001 or bc_002.... The problem is if I hard code this value i.e bc_001 in my query it fetches the result correctly however when I use the variable $sku in my query it does not work.

1
  • Simplify your CodeIgniter script: return $this->db->get_where('barcode_sku', ['sku' => $sku])->row('quantity'); Commented Nov 3 at 19:47

3 Answers 3

1

Because you're using single quotes to warp your query statement php will not prase the variable inside that query, instead use the double quotations to allow php to interpret the $sku variable.

 $query = $this->db->query("SELECT * FROM barcode_sku WHERE sku = \"$sku\"");

Also don't forget to escape $sky variable to avoid SQL Injections.

a better solution is to use codeigniter active record.

http://www.codeigniter.com/userguide2/database/active_record.html

Sign up to request clarification or add additional context in comments.

Comments

0

may be you can modify the query like this:

public function getOne($sku){

    $ans = 0;
    $sql= 'SELECT * FROM barcode_sku WHERE sku = ?';
    $query = $this->db->query($sql, array($sku));
    $res = $query->result();
    $row = $res[0];
    $ans =  $row->quantity;


    return $ans;
}

Comments

0

please try this --

public function getOne($sku)
{
    $this->db->select('*');
    $this->db->from('barcode_sku');
    $this->db->like('sku ', $sku,'after');
    $query = $this->db->get();
    return $query->result_array();
}

it will return a array..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.