Now, how about doing the same thing with PHP - fire a SELECT query at the database, and display the results in an HTML page? And here's what's the output looks like: As you can see, using PHP to get data from a PostgreSQL database involves several steps, each of which is actually a pre-defined PHP function. Let's dissect each step: 1. The first thing to do is specify some important information needed to establish a connection to the database server. This information includes the server name, the username and password required to gain access to it, and the name of the database to query. These values are all set up in regular PHP variables. 2. In order to begin communication with the PostgreSQL database server, you first need to open a connection to the server. All communication between PHP and the database server takes place through this connection. In order to initialize this connection, PHP offers the pg_connect() function. The function requires a connection string containing one or more parameters - these could include the host name, port, database name, user name and user password. Here are some examples of valid connection strings: This function then returns a "link identifier", which is stored in the variable $connection; this identifier is used throughout the script when communicating with the database. 3. Now that you have a connection to the database, it's time to send it a query via the pg_query() function. This function needs two parameters: the link identifier for the connection and the query string. The result set returned by the function above is stored in the variable $result. 4. This result set may contain, depending on your query, one or more rows or columns of data. You then need to retrieve specific sections or subsets of the result set with different PHP functions - the one used here is the pg_num_rows() function, which counts the number of rows and returns the value needed. There are several other alternatives you can use at this point, which will be explained a little further down. 5. Finally, each database connection occupies some amount of memory - and if your system is likely to experience heavy load, it's a good idea to use the pg_close() function to close the connection and free up the used memory. Simple, ain't it?
blog comments powered by Disqus |