简体   繁体   中英

Database problems using model in CodeIgniter

Again a question about CodeIgniter. I'm trying to get information out of my database, which is not that dificult. I get all the data but want to add an condition, the author_id has to be the same as $id. My code:

<?php
class BookModel extends CI_Model {

    public function get_book($id){
        $this->load->database();
        $query = $this->db->query('SELECT book_id, book_title, book_publisher, book_summary FROM books WHERE author_id = $id');
            return $query->result();
        }
}
?>

If I echo $id it shows my ID. But in the SQL function it is failing. Also, when i hardcode a number like

WHERE author_id = 1

It load proberly.

This is the error i get:

Error Number: 1054

Unknown column '$id' in 'where clause'

SELECT book_id, book_title, book_publisher, book_summary FROM books WHERE author_id = $id

What am I doing wrong?

You have two problems.

Firstly, MySQL uses single = for both assignment and comparison, not ==.

Secondly, variables in PHP are parsed only in double-quoted strings, not single.

So '...$id' will be parsed literally as $id , not the value of the variable $id . Convert to double quotes.

Or, use CI binding - it's better for security, and you don't have to worry about escaping, quotes etc.

$sql = 'SELECT ... FROM books WHERE author_id = ?';
$query = $this->db->query($sql, array($id));

since you are using codeigniter,use the ci database class functions,they will make your task simpler and you have not to worry for sql injection .You can do it in simpler way like this

    public function get_book($id)
      {
        $this->load->database();
        $this->db->select('book_id, book_title, book_publisher, book_summary');
        $this->db->from('books');
        $this->db->where('auther_id',$id);
        $data=$this->db->get();
        return $data->result();
       }

改变这个

$query = $this->db->query("SELECT book_id, book_title, book_publisher, book_summary FROM books WHERE author_id =".$id);

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