pg_query
(PHP 4 >= 4.2.0, PHP 5)
pg_query — Execute a query
Описание
pg_query() executes the query on the specified database connection .
If an error occurs, and FALSE is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.
Замечание: Although connection can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.
Замечание: This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.
Список параметров
- connection
-
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
- query
-
The SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.
Возвращаемые значения
A query result resource on success, or FALSE on failure.
Примеры
Пример #1 pg_query() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occured.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>
Пример #2 Using pg_query() with multiple statements
<?php
$conn = pg_pconnect("dbname=publisher");
// these statements will be executed as one transaction
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";
pg_query($conn, $query);
?>
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- PostgreSQL
- pg_affected_rows
- pg_cancel_query
- pg_client_encoding
- pg_close
- pg_connect_poll
- pg_connect
- pg_connection_busy
- pg_connection_reset
- pg_connection_status
- pg_consume_input
- pg_convert
- pg_copy_from
- pg_copy_to
- pg_dbname
- pg_delete
- pg_end_copy
- pg_escape_bytea
- pg_escape_identifier
- pg_escape_literal
- pg_escape_string
- pg_execute
- pg_fetch_all_columns
- pg_fetch_all
- pg_fetch_array
- pg_fetch_assoc
- pg_fetch_object
- pg_fetch_result
- pg_fetch_row
- pg_field_is_null
- pg_field_name
- pg_field_num
- pg_field_prtlen
- pg_field_size
- pg_field_table
- pg_field_type_oid
- pg_field_type
- pg_flush
- pg_free_result
- pg_get_notify
- pg_get_pid
- pg_get_result
- pg_host
- pg_insert
- pg_last_error
- pg_last_notice
- pg_last_oid
- pg_lo_close
- pg_lo_create
- pg_lo_export
- pg_lo_import
- pg_lo_open
- pg_lo_read_all
- pg_lo_read
- pg_lo_seek
- pg_lo_tell
- pg_lo_truncate
- pg_lo_unlink
- pg_lo_write
- pg_meta_data
- pg_num_fields
- pg_num_rows
- pg_options
- pg_parameter_status
- pg_pconnect
- pg_ping
- pg_port
- pg_prepare
- pg_put_line
- pg_query_params
- pg_query
- pg_result_error_field
- pg_result_error
- pg_result_seek
- pg_result_status
- pg_select
- pg_send_execute
- pg_send_prepare
- pg_send_query_params
- pg_send_query
- pg_set_client_encoding
- pg_set_error_verbosity
- pg_socket
- pg_trace
- pg_transaction_status
- pg_tty
- pg_unescape_bytea
- pg_untrace
- pg_update
- pg_version
Коментарии
$GLOBALS["PG_CONNECT"]=pg_connect(...);
....
function query ($sqlQuery,$var=0) {
if (!$GLOBALS["PG_CONNECT"]) return 0;
$lev=error_reporting (8); //NO WARRING!!
$result=pg_query ($sqlQuery);
error_reporting ($lev); //DEFAULT!!
if (strlen ($r=pg_last_error ($GLOBALS["PG_CONNECT"]))) {
if ($var) {
echo "<p color=\"red\">ERROR:<pre>";
echo $sqlQuery;
echo "</pre>";
echo $r;
echo "</p>";
}
close_db ();
return 0;
}
return $result;
}
Use pg_query to call your stored procedures, and use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure.
<?php
$pgConnection = pg_connect("dbname=users user=me");
$userNameToCheckFor = "metal";
$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");
$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');
?>
One thing to note that wasn't obvious to me at first. If your query returns zero rows, that is not a "failed" query. So the following is wrong:
$result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
if (!$result) {
echo "No a=b in x\n";
}
pg_query returns FALSE if the query can not be executed for some reason. If the query is executed but returns zero rows then you get back a resul with no rows.
expanding on the note left by "cmoore" -
To check to see if the recordset returned no records,
<?php
$result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
if (!$result) {
echo "query did not execute";
}
$rs = pg_fetch_assoc($result);
if (!$rs) {
echo "0 records"
}
?>
-jack
Improving upon what jsuzuki said:
It's probably better to use pg_num_rows() to see if no rows were returned, as that leaves the resultset cursor pointed to the first row so you can use it in a loop.
Example:
<?php
$result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
if (!$result) {
echo "query did not execute";
}
if (pg_num_rows($result) == 0) {
echo "0 records"
}
else {
while ($row = pg_fetch_array($result) {
//do stuff with $row
}
}
?>
I, personally, also find it more readable.
There was a typo in the code that I posted:
<?php
$result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
if (!$result) {
echo "query did not execute";
}
if (pg_num_rows($result) == 0) {
echo "0 records"
}
else {
while ($row = pg_fetch_array($result)) {
//do stuff with $row
}
}
?>
It would be better this way:
<?php
$result=pg_query($conn, "SELECT COUNT(*) AS rows FROM x WHERE a=b;");
if (!$result) {
echo "query did not execute";
}
if ($line = pg_fetch_assoc($result)) {
if ($line['rows'] == 0) {
echo "0 records"
}
}
else {
while ($row = pg_fetch_array($result)) {
//do stuff with $row
}
}
?>
This solution doesn't raise the load of the system with the move of matching rows (perhaps 0,1, perhaps 100, 1000, ... rows)
A quick note for novice users: when gathering input from fields on a web form that maintains a database connection, *never* use pg_query to do queries from the field. Always sanitize input using pg_prepare and pg_execute.
Here is my small function to make it easier for me to use data from select queries (attention, it is sensitive to sql injection)
<?php
function requestToDB($connection,$request){
if(!$result=pg_query($connection,$request)){
return False;
}
$combined=array();
while ($row = pg_fetch_assoc($result)) {
$combined[]=$row;
}
return $combined;
}
?>
Example:
<?php
$conn = pg_pconnect("dbname=mydatabase");
$results=requestToDB($connect,"select * from mytable");
//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";
$mycell=$results[$rownumber][$columname];
var_dump($mycell);