pg_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_queryクエリを実行する

説明

pg_query(resource $connection = ?, string $query): resource|false

pg_query() は、指定したデータベース connection 上で query を実行します。 特別な理由がない限り、この関数よりも pg_query_params() を使うほうがいいでしょう。

エラーが発生して false が返された場合、もし接続が正常なら pg_last_error() 関数を使用してエラーの詳細情報が 取得可能です。

注意: connectionは省略可能ですが、それは推奨されません。 なぜならスクリプトのバグが発見しにくくなるためです。

注意:

この関数は、以前は pg_exec() と呼ばれていました。 pg_exec() は互換性確保のためにまだ使用可能ですが、 新しい名前を使用することが推奨されています。

パラメータ

connection

PostgreSQL データベース接続リソース。connection が指定されていない場合はデフォルトの接続が使用されます。 デフォルトの接続は、直近の pg_connect() あるいは pg_pconnect() によって作成されたものです。

query

実行する 1 つまたは複数の SQL 文。複数の文が関数に渡された場合は、 明示的に BEGIN/COMMIT コマンドを指定していない限りはそれらの文は ひとつのトランザクションとして実行されます。しかし、1 回のコールで 複数のトランザクションを実行することは推奨されません。

警告

ユーザーから受け取ったデータを文字列に直接組み込むのは危険で、SQL インジェクション の脆弱性を引き起こしがちです。クエリ文字列に直接埋め込むのではなく、 pg_query_params() を使ってパラメータとして指定することを推奨します。

ユーザーから受け取ったデータをクエリ文字列に直接埋め込む場合は、 適切にエスケープ する必要があります。

返り値

成功した場合にクエリ結果リソース、失敗した場合に false を返します。

例1 pg_query() の例

<?php

$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

$result pg_query($conn"SELECT author, email FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

while (
$row pg_fetch_row($result)) {
  echo 
"Author: $row[0]  E-mail: $row[1]";
  echo 
"<br />\n";
}
 
?>

例2 pg_query() で複数の文を使用する例

<?php

$conn 
pg_pconnect("dbname=publisher");

// これらの文がひとつのトランザクションとして実行されます

$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);

?>

参考

add a note add a note

User Contributed Notes 15 notes

up
5
a dot mcruer at live dot com
10 years ago
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.
up
5
hierophantNOSPAM at pcisys dot net
21 years ago
Regarding david.bouriaud@ac-rouen.fr:
You misunderstand SQL. When a query is issued, results applicable at the time of the query are returned to the application (i.e. PHP). There is no further reference to the database required. Thus, all of the pg_fetch_* functions are acting on an internal data storage, NOT the database itself. This is because SQL does not have a concept of sets, or of state (except in limited circumstances provided by transactions). However, if you use a cursor instead, fetching only one record at a time, you may get an error if you delete the table. If you don't, it is an issue with Postgres, not PHP.
up
2
Jan-Willem Regeer
18 years ago
In reply to david dot bouriaud at ac-rouen dot fr:

All it is doing is internal caching. How can that be dangerous. If you are going to be deleting records after you have closed the connection it is your problem to make sure you have the latest and greatest records, and not some cached ones. Considering you are writing the script I don't see why it is a problem, you know what you are doing in the script, so it is quite useless for PHP to invalidate the cache, when that could be done upon exiting the script, which would mean there was less time spent cleaning out the cache when it counts most (when returning data to the user).
up
3
jsuzuki at spamcop dot net
18 years ago
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
up
2
zoli at makettinfo.hu
17 years ago
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)
up
2
mankyd
17 years ago
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
  
}
  }
?>
up
1
cmoore
18 years ago
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.
up
0
mankyd
17 years ago
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.
up
0
mentat at azsoft dot pl
21 years ago
$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 "&lt/p>";
      }
      close_db ();
      return 0;
   }
   return $result;
}
up
-1
Anonymous
10 years ago
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);
up
-2
Akbar
19 years ago
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');
?>
up
-3
david dot bouriaud at ac-rouen dot fr
21 years ago
Hi to all !
It seems that the old pg_exec function does not do what it is expected to.
In the doc, it is said that it returns a resource identifier on the successful querry that was send to the backend.
It seems to me that it is more than a resource identifier.
Follow the example :

<?php
$ConnId
= pg_connect ("blablabla");
$ResId = pg_exec ("select * from table", $ConnId);
pg_close ($ConnId);
$row = pg_fetch_array ($ResId, 4);
?>

I closed the connection voluntarily before the pg_fetch_array. It WORKS !

Now, imagine the following script :
<?php
$ConnId
= pg_connect ("blablabla");
$ResId = pg_exec ("select * from table", $ConnId);
pg_close ($ConnId);
system ("psql base -c delete from table");
$row = pg_fetch_array ($ResId, 4);
?>
See how it could be harmful !!!! I think that the coders have done this for performances reasons, but it is not the right way do do so !!!
up
-4
yoshinariatsuo at yahoo dot com
21 years ago
create table from pg_query results.. hope it helps newbies...
function table_create($result)
{
    $numrows = pg_num_rows($result);
    $fnum = pg_num_fields($result);

    echo "<table border width='100%'>";
    echo "<tr>";

    for ($x = 0; $x < $fnum; $x++) {
        echo "<td><b>";
        echo strtoupper(pg_field_name($result, $x));
        echo "</b></td>";
    }

    echo "</tr>";

    for ($i = 0; $i < $numrows; $i++) {
        $row = pg_fetch_object($result, $i);
        echo "<tr align='center'>";
        for ($x = 0; $x < $fnum; $x++) {
    $fieldname = pg_field_name($result, $x);
    echo "<td>";
    echo $row->$fieldname;
    echo "</td>";
        }
        echo"</tr>";
    }
    echo "</table>";
   
    return 0;
}
up
-5
sd at dicksonlife dot com
17 years ago
Took me a while to track this down so I thought it might be useful for others:

If you use stored procedures and need to get result sets back from them:

function dbquery($link,$query){
  pg_query($link,"BEGIN;");
  $tr=pg_query($link,$query);
  $r=pg_fetch_row($tr);
  $name=$r[0];
  $rs=pg_query($link,"FETCH ALL IN \"" . $name . "\";");
  pg_query($link,"END;");
  return $rs;
}

(Error checking removed for clarity)
up
-8
jvarner at dsrglobal dot com
21 years ago
That's why your code should never assume it has the very latest data unless it locks it.
To Top