문제

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;

    }
도움이 되었습니까?

해결책

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)

다른 팁

The ? are placeholder the values of which are filled in in the $sth->execute( array( 'active', $language_id ) ) statement.

One of the main purposes for this construct is to prevent sql injection attacks.

Its a Used to set the value dynamically ,in other words place holder

These are "parametrized queries". While evaluating "?" are replaced with given values (it's called binding). They protect from sql injection and makes possible to optimize queries.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top