Contents / Previous / Next


Getting Info about Query Results

The argument to the following functions is always a result resource returned by pg_query().

int pg_num_rows ( resource result):
Returns the number of rows in a PostgreSQL result resource or -1 on error.

int pg_affected_rows ( resource result):
Returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries executed by pg_query(). If no tuple is affected by this function, it will return 0.

int pg_num_fields ( resource result):
Returns the number of fields (columns) in a PostgreSQL result or -1 on error.

int pg_result_status ( resource result):
Returns the status of a query result given the result resource. Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_TO, PGSQL_COPY_FROM, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR. See also pg_connection_status().

Example:

<? $con = "dbname=workshop user=felix"; $dbh = pg_connect( $con ); if( $dbh ) { $query_str= "SELECT * FROM stud WHERE id=17;"; $res = pg_query( $dbh, $query_str ); echo "<P>"; echo "query status: ".pg_result_status( $res )."<BR>"; echo "num rows: ".pg_num_rows( $res )."<BR>"; echo "num fields: ".pg_num_fields( $res )."<BR>"; if ( pg_num_rows( $res ) ) { $query_str= "DELETE FROM stud WHERE id=17;"; $res_del = pg_query( $dbh, $query_str ); echo "<P>deleted rows: ".pg_affected_rows( $res_del )."<P>"; pg_free_result ( $res_del ); } pg_free_result ( $res ); $query_str= "INSERT INTO stud (id, name, gender, diploma ) VALUES (17, 'sven', 'm', 'bio' );"; $res = pg_query( $dbh, $query_str ); echo "<P>affected rows: ".pg_affected_rows( $res )."<P>"; echo ( "<P>close: ".pg_close( $dbh )."<P>\n" ); pg_free_result ( $res ); } else { echo "connection error<BR>\n"; } // Output if id 17 was already in stud table: // // query status: 2 // num rows: 1 // num fields: 5 // // deleted rows: 1 // // affected rows: 1 // // close: 1 ?>