tags:

views:

102

answers:

1

How do you read the following code about pg_query_params and pg_prepare?

$result = pg_query_params ( $dbconn,        
    "SELECT flagged_for_moderator_removal           // unsure about Repetition here
    FROM questions 
    WHERE question_id = $1",
    array ( $_GET['question_id'] ) );

if ( pg_num_rows ( $result ) == 0 ) { 
    $result = pg_prepare ( $dbconn, "get_flagged_status_list",    
        "SELECT flagged_for_moderator_removal       // unsure about Repetition here
        FROM questions 
        WHERE question_id = $1"
    );  
}

This question is related to my thread where I do not want to declare twice the prepared statement.

The difference between statements is that the other has a name *get_flagged_status_list*, while the other one does not. I understand the code as follows

Iteration |  1                     2
----------------------------------------------------------------------
           run pg_query_params    run pg_qeury_params
           run pg_prepare         
           run pg_execute         run pg_execute

However, this is not true, since the code runs pg_prepare in the second iteration too. 1.

+2  A: 

Your posted example does not make sense - pg_prepare() and pg_query_params() are independent functions with different purposes that you would not normally use in conjunction.

pg_prepare() prepares a statement (a query) for later execution via pg_execute(). This is done as an potential optimization - if you know in advance that you will need to execute the statement many times in a row, preparing it upfront can save some work on the database server, since it does not have to (re-)prepare the statement for each call.

pg_query_params() (as well as its 'simpler' version pg_query()) just executes the statement (query) directly, forcing the database server to (re)prepare the statement each time the function gets called.

So in short, this

$result = pg_query_params($query, $params);

will give you the exact same result as this

$statement = pg_prepare($query);
$result = pg_execute($statement, $params);

The only difference is that in the second case, you still have the prepared statement, ready to reuse for more calls to pg_execute() - which is why you can give it a name, since that way you can have different prepared statements on the same connection that you can execute as you please, many times, in arbitrary order.

Henrik Opel
I have the `pg_prepare` inside a function. **How can you restrict the re-declaration of the prepared statement?** - I obviously need to remove the *pg_query_params*.
Masi
If it is inside a function, either move the pg_prepare call outside the function (and remove pg_query_param), or just remove the pg_prepare call and use only pg_query_param. Is there a reason why you want to use pg_prepare? It smells like premature optimization.
Henrik Opel
Thank you a lot for your answer! It is really helpful.
Masi