1.
To allow PHP to support PostgreSQL, you need to re-compile PHP;
. /Configure -- prefix =/usr/local/php5 -- with-apxs2 =/usr/local/apache2/bin/apxs -- with-mysql =/usr/local/mysql -- with-config- file-path =/usr/local/php5 -- with-zlib -- enable-mbstring = all -- with-mysqli =/usr/local/mysql/bin/mysql_config -- with-pdo- mysql =/usr/local/mysql-- With-pgsql =/usr/local/pgsql
The last parameter specifies the path of pgsql (note that this is your own pgsql path !)
Then:
Make
Sudo make install
2.
If Apache has been started, restart Apache:
Sudo apachectl restart
3.
To test, we first create a test database:
Enter the following command on the terminal:
Createdb classdb
Psql classdb
Create table class (id int, name varchar (20), email varchar (20 ));
4.
Create an index. php file in the Apache Web root directory. The content is as follows:
<? Php
$ Conn = pg_connect ("host = localhost port = 5432 dbname = classdb user = postgresql password = postgresql ");
If ($ conn ){
Print "OK! Has connected "." <br> ";
} Else {
Print "Error! Connect failure "." <br> ";
}
?>
Note: You need to modifyRelated Parameters of pg_connect! (5432 is the default port of pgsql, just like port 3306 of mysql.)
DisplayOK! Has connected. indicates that pgsql Has been connected.
5.
Then we insert records into pgsql in php, and modify index. php as follows:
<? Php
$ Conn = pg_connect ("host = localhost port = 5432 dbname = classdb user = postgresql password = postgresql ");
If ($ conn)
{
Print "OK! Has connected "." <br> ";
}
Else
{
Print "Error! Connect failure "." <br> ";
}
?>
</Br>
<Form action = "index. php" method = "post">
<Table>
<Caption> <strong> Insert </strong> </caption>
<Tr>
<Td> <strong> id: </strong> </td>
<Td> <input type = "text" name = "id"> </input> </td>
<Tr>
<Td> <strong> name: </strong> </td>
<Td> <input type = "text" name = "name"> </input> </td>
<Tr>
<Td> <strong> email: </strong> </td>
<Td> <input type = "text" name = "email"> </input> </td>
<Tr>
<Tr>
<Td> <input type = "submit" value = "INSERT"> </input> </td>
</Tr>
</Table>
</Form>
<? Php
// Insert
$ Id = $ _ POST ["id"];
$ Name = $ _ POST ["name"];
$ Email = $ _ POST ["email"];
If ($ id & $ name & $ email)
{
$ Query = "insert into class VALUES ($ id, '$ name',' $ email ')";
$ Result = pg_query ($ query );
}
// Select
$ Query = 'select * FROM class ';
$ Result = pg_query ($ query );
?>
<Table border = "1">
<Tr> <th> id </th> <th> name </th> <th> email </th> </tr>
<? Php
While ($ line = pg_fetch_array ($ result, null, PGSQL_ASSOC ))
{
Echo "<tr> ";
Foreach ($ line as $ col_value)
{
Echo "<td> $ col_value </td> ";
}
Echo "</tr> ";
}
Echo "</table> ";
// Release the result set
Pg_free_result ($ result );
// Close the connection
Pg_close ($ conn );
?>
In the browser: http: // localhost/index. php, you can see the effect.