【问题标题】:how to pass variable value to sql query in codeigniter?如何将变量值传递给codeigniter中的sql查询?
【发布时间】:2017-06-13 01:10:55
【问题描述】:

是否可以在codeigniter的mysql查询中传递变量值?

我想从数据库中选择 ID 与我的会话 ID 相同的记录。

我的代码是:

$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('products');        
$this->db->where('id_admin = (SELECT id_admin FROM users WHERE id='.$this->session->userdata('user_id').')', NULL, TRUE);

我们可以在数据库查询中连接变量值吗?

这段代码没有给出任何错误,但也没有给出任何结果。

【问题讨论】:

  • 利用join。
  • 尝试如下答案。

标签: php mysql codeigniter


【解决方案1】:

在活动记录中使用联接

    $this->db->select('p.*');
    $this->db->from('products as p'); 
    $this->db->join('users','p.id_admin=users.id');
    $this->db->where('users.id',$this->session->userdata('user_id'),false);
    $query = $this->db->get();

【讨论】:

    【解决方案2】:

    如何根据活动记录的文档在 CI 中编写 JOIN 查询的示例参考。

    $article_id = $this->input->post('article_id');
    $this->db->select('*');
    $this->db->from('articles');
    $this->db->join('news', 'news.id = articles.id');
    $this->db->where('articles.id',$article_id);
    $query = $this->db->get();
    

    上面的代码会产生如下的查询来执行。

    SELECT * FROM articles JOIN news ON news.id = articles.id WHERE articles.id='10'
    

    如果传递的 id 是 10

    为了查看执行查询的结果,您必须执行以下代码。

    print_r($query->result());
    

    【讨论】:

      【解决方案3】:

      像这样尝试..使用两个表的连接。

      <?php
      $this->db->select('products.*');
      $this->db->from('products'); 
      $this->db->join('users','products.id_admin=users.id_admin');
      $this->db->where('users.id',$this->session->userdata('user_id'));
      
      $query = $this->db->get();
      
      print_r($query->result_array());//your array of records
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多