0
votes

is it possible to pass the variable value in mysql query in codeigniter ?

I want to select records from database that have id same as my session id.

my code is :

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

can we concatenate variable values in database queries?

This code not given any error, but not give any result also.

3
make use of join. - Hikmat Sijapati
try like as below answer. - Hikmat Sijapati

3 Answers

2
votes

Use join in active records

    $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();
1
votes

An Example Reference of how to write the JOIN Query in CI as per the Documentation of the Active Records.

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

The above code will produce the query as follows for execution.

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

Provided the passed id is 10

In order to view the Result of the executed query you must perform the below code.

print_r($query->result());
1
votes

Try like this..use joining of two tables.

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