Reputation: 55
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?
Upvotes: 0
Views: 130
Reputation: 853
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();
}
Upvotes: 1
Reputation: 34556
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));
Upvotes: 1
Reputation: 365
change this
$query = $this->db->query("SELECT book_id, book_title, book_publisher, book_summary FROM books WHERE author_id =".$id);
Upvotes: 0