简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM