Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing column names with pg_fetch_row in PHP

Tags:

php

postgresql

How can you reference column names with PHP's pg_fetch_row?

Example about the code which we have been debugging with Cha.

$dbconn = pg_connect("host=localhost port=5432 dbname=noa user=noa password=123");
$result_titles_tags = pg_prepare( $dbconn, "query777",
    "SELECT question_id, title
    FROM questions
    WHERE question_id IN
    (    
        SELECT question_id
        FROM questions
        ORDER BY was_sent_at_time
        DESC LIMIT 50
    )
    ORDER BY was_sent_at_time
    DESC LIMIT 50;"
);
$result_titles = pg_execute( $dbconn, "query777", array());


while($row = pg_fetch_row( $result_titles )) {
    $question_id = $row[0];                   // This works but following does not
       // We cannot use here `$question_d = $row['question_id']      
                // Problem here: 
                // What is the reason that you cannot use $row['question_id']?
       // for some unknown reason
       //  
like image 523
Léo Léopold Hertz 준영 Avatar asked Aug 16 '09 06:08

Léo Léopold Hertz 준영


1 Answers

You're looking for pg_fetch_assoc, which returns an associative array--i.e., you can call the fields by name.

pg_fetch_array allows you to call them by either name or index. pg_fetch_object allows you to refer to them as $row->question_id.

Choose whichever one you like best. There's no real appreciable speed difference.

like image 158
Eric Avatar answered Oct 18 '22 05:10

Eric