PHP is used for Web browser access to POSTGRESQL. With PHP, database commands can be embedded in Web pages.
Two Web pages are required for our state code application:
one for data entry and another for display. Figure
shows a Web page that allows entry of a state code.
<!--
-- PHP sample program -- input
-->
<HTML>
<BODY>
<!-- prompt user for a state code -->
<FORM ACTION="<? echo $SCRIPT_NAME ?>/pg/sample2.phtml?state_code" method="POST">
State Code:
<INPUT TYPE="text" name="state_code" value="<? echo $state_code ?>"
maxlength=2 size=2>
<BR>
<INPUT TYPE="submit" value="Continue">
</FORM>
</BODY>
</HTML>
Figure shows a second Web
page that performs a SELECT and displays the results.
<!--
-- PHP sample program -- output
-->
<HTML>
<BODY>
<?
$database = pg_Connect("", "", "", "", "test"); # connect to the database
if (!$database) # did the database connection fail?
{
echo "Connection to database failed.";
exit;
}
$result = pg_Exec($database, # send the query
"SELECT name " .
"FROM statename " .
"WHERE code = '$state_code'");
for ($i = 0; $i < pg_NumRows($result); $i++) # loop through all rows returned
{
echo pg_Result($result,$i,0); # print the value returned
echo "<BR>";
}
?>
</BODY>
</HTML>
Normal Web page commands (HTML tags) begin with < and end with >. By contrast, PHP code begins with <? and ends with ?>. The PHP interface does not ship with POSTGRESQL, but can be downloaded from http://www.php.net.