views:

871

answers:

2

This is what I'd like to do, but it doesn't seem possible: (edit: changed single to double quotes)

function get_archives($limit, $offset) 
{
    $query = $this->db->query("
        SELECT  archivalie.id, 
                archivalie.signature, 
                type_of_source.description AS type_of_source_description, 
                media_type.description AS media_type_description,
                origin.description AS origin_description

        FROM    archivalie, 
                type_of_source, 
                media_type,
                origin

        WHERE   archivalie.type_of_source_id = type_of_source.id                                                        
        AND     type_of_source.media_type_id = media_type.id  
        AND     archivalie.origin_id = origin.id                                                                     

        ORDER BY    archivalie.id ASC
     LIMIT       $limit, $offset
    "); 


    // etc...

}

It gives this error: (edit: new error message using double quotes, and with an offset number passed in the URL)

ERROR: LIMIT #,# syntax is not supported HINT: Use separate LIMIT and OFFSET clauses.

It only works if you pass the variables using the ActiveRecord format:

$this->db->select('archivalie.id, archivalie.signature, etc, etc');
// from, where, etc.
$this->db->limit($limit, $offset);        
$query = $this->db->get();
A: 

If you used double quotes instead of single quotes it would work, but you'd be open to an injection attack if the variables weren't sanitized properly.

Greg
Perhaps I'm missing something, but why would single versus double quotes make a difference to SQL injection attacks?
Thomas Owens
I'm with Thomas. I don't get what Greg means with this.
Thorpe Obazee
Because you're passing a variable directly into an SQL statement - you should escape it first.
Greg
Question was changed after I answered btw
Greg
+1  A: 

This worked:

$query = $this->db->query("
    SELECT  archivalie.id, 
            archivalie.signature, 
            type_of_source.description AS type_of_source_description, 
            media_type.description AS media_type_description,
            origin.description AS origin_description

    FROM    archivalie, 
            type_of_source, 
            media_type,
            origin

    WHERE   archivalie.type_of_source_id = type_of_source.id                                                        
    AND     type_of_source.media_type_id = media_type.id  
    AND     archivalie.origin_id = origin.id                                                                     

    ORDER BY    archivalie.id ASC
    LIMIT       $limit
    OFFSET      $offset
");

But it requires a check to assign a default value if no offset is present in the URL. From my controller:

# Check/assign an offset
$offset = (!$this->uri->segment(3)) ? 0 : $this->uri->segment(3);

# Get the data
$archives = $this->archive->get_archives($config['per_page'], $offset);
meleyal