Dayem Siddiqui
Dayem Siddiqui

Reputation: 215

CodeIgniter fetching data from database

hey I am new to codeigniter. 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. please help.

Upvotes: 1

Views: 167

Answers (3)

Sorav Garg
Sorav Garg

Reputation: 1067

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..

Upvotes: 0

Fake Face
Fake Face

Reputation: 116

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;
}

Upvotes: 0

skmail
skmail

Reputation: 423

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

Upvotes: 1

Related Questions