Search code examples
sqlpear

What does it mean "?" in sql query?


I just got a query cod :

SELECT o.id,o.sort_order,od.object FROM i_objects o, i_objects_description od 
WHERE o.id=od.objects_id AND o.object_status = ? AND od.languages_id = ? 
ORDER BY o.sort_order ASC

I want figure it out what does "?" mean in this query ? If I run this query , it gives me this error :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? 

Im using PEAR and this is my function :

function getArrayObjects( $language_id )
    {

        $q = 'SELECT o.id,o.sort_order,od.object FROM ' . TABLE_OBJECTS . ' o, ' . TABLE_OBJECTS_DESCRIPTION . ' od ';
        $q.= 'WHERE o.id=od.objects_id AND o.object_status = ? AND od.languages_id = ? ';
        $q.= 'ORDER BY o.sort_order ASC';

        $sth = $this->_db->prepare( $q );

        $res = $sth->execute( array( 'active', $language_id ) );
        //var_dump($res);echo "<br>";echo "<br>";echo "<br>";
        $objects = array();
        while( $row = $res->fetchRow())
        {
            $objects[$row['id']] = $row;
        }

        return $objects;

    }

Solution

  • It's a placeholder for parameter. In your query you have this:

    AND o.object_status = ? AND od.languages_id = ?
    

    And then you execute it like this:

    $res = $sth->execute( array( 'active', $language_id ) );
    

    So, when query is actually executed by database server, object_status is 'active' and language_id is $language_id.

    This is done this way to guard from SQL injection. Another reason is efficiency. When you use prepared statements, database doesn't need to parse/compile query each time. It uses the template and just substitutes values in it. (more on this: Prepared statement)