简体   繁体   English

CodeIgniter中使用模型的数据库问题

[英]Database problems using model in CodeIgniter

Again a question about CodeIgniter. 再次是关于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. 我获取了所有数据,但想添加一个条件,author_id必须与$ 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. 如果我回显$ id,则显示我的ID。 But in the SQL function it is failing. 但是在SQL函数中却失败了。 Also, when i hardcode a number like 另外,当我硬编码一个数字

WHERE author_id = 1 在哪里author_id = 1

It load proberly. 它会加载详细信息。

This is the error i get: 这是我得到的错误:

Error Number: 1054 错误编号:1054

Unknown column '$id' in 'where clause' “ where子句”中的未知列“ $ id”

SELECT book_id, book_title, book_publisher, book_summary FROM books WHERE author_id = $id 从其中where author_id = $ id的书籍中选择book_id,book_title,book_publisher,book_summary

What am I doing wrong? 我究竟做错了什么?

You have two problems. 你有两个问题。

Firstly, MySQL uses single = for both assignment and comparison, not ==. 首先,MySQL使用single =进行赋值和比较,而不是==。

Secondly, variables in PHP are parsed only in double-quoted strings, not single. 其次,PHP中的变量仅以双引号引起来,而不是单引号。

So '...$id' will be parsed literally as $id , not the value of the variable $id . 因此, '...$id'将按字面意义解析为$id ,而不是变量$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. 或者,使用CI绑定-更好的安全性,而您不必担心转义,引号等问题。

$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 由于您正在使用codeigniter,因此请使用ci数据库类函数,它们将使您的任务更简单,并且您不必担心sql注入。您可以像这样简单地进行操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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