phpmysqlcodeignitersubquerywhere-in

How to inject variables as values and identifiers in a SQL string executed by CodeIgniter's query()


I'm trying to run the following sample query in Codeigniter:

SELECT users.id, users.first_name, users.last_name, users.game_id
FROM users
WHERE users.id NOT IN (SELECT banned.users_id FROM banned)
AND game_id = '1'
ORDER BY last_name

This works in MySQL. However, I require game_id, '1' and last_name to be variables something like:

MODEL

function get_where_custom_ordered_checked($col, $value, $order_by) {
    $query = $this->db->query('
        SELECT users.id, users.first_name, users.last_name, users.game_id
        FROM users
        WHERE users.id NOT IN (SELECT banned.users_id FROM banned)
        AND $col = $value
        ORDER BY $order_by
        ');
    return $query;
}

Obviously this doesn't work, and the query doesn't recognise the variable.

How would I parameterize the CodeIgniter per the MySQL query variables, especially inside the subquery against a second table?

I have also tried using SET but still no avail:

MODEL

function get_where_custom_ordered_checked($col, $value, $order_by) {
    $query1 = 'SET @col = '$col', @value = '$value', @order_by = '$order_by'';
        $this->db->query($query1);
        $query2 = $this->db->query('
            SELECT users.id, users.first_name, users.last_name, users.game_id
            FROM users
            WHERE users.id NOT IN (SELECT players_phases.players_id FROM players_phases)
            AND @col = @value
            ORDER BY @order_by
            ');
    $query = $this->db->query($query2);
    return $query;
}

I've tried breaking it down to use the Codeigniter Active Record Class, but I don't know how to include the where_not_in() inside a where(), especially since I need to run the NOT IN query against a second table - unlike the where_not_in() examples shown in the Active Records CI documentation where it is against the same table.


Solution

  • Use the following code. Generally anything which is given within the single quotes consider as a string, so it doesn't recognize the variables.

    function get_where_custom_ordered_checked($col, $value, $order_by) {
    
        $query = $this->db->query('
                                    SELECT users.id, users.first_name, users.last_name, users.game_id
                                    FROM users
                                    WHERE users.id NOT IN
                                    (SELECT banned.users_id FROM banned) AND '.$col.' = '.$value.'
                                    ORDER BY '.$order_by.'
                                    ');
        return $query;
    }