944,066 Members | Top Members by Rank

Ad:
  • PHP Code Snippet
  • Views: 7209
  • PHP RSS
0

Accessing PostgreSQL Database from PHP

by on Apr 20th, 2005
This code snippet will attempt to show newbies to php how to connect and retrieve data from a PostgreSQL Database Server using PHP.
PHP Code Snippet (Toggle Plain Text)
  1. <?php
  2. // Initiate the connection
  3. $conn = pg_connect('dbname=<database>');
  4. /*
  5. <database> is the name of your database. It is assumed to reside on the server you are running this code from
  6. Alternatively use something like this:
  7. $conn = pg_connect('host=myserver port=5432 dbname=database user=someuser password=secret');
  8. */
  9. if (!$conn) { // Check if valid connection
  10. // NO, some error occured
  11. echo "Error Connecting to database<br>";
  12. exit;
  13. // add your error handling function here or just exit :)
  14. } else {
  15. // Valid connection, we can go on to retrieve some data
  16. /*
  17. Assume we have a table with user data called user_table
  18. Username Password Userlevel
  19. user1 pass1 1
  20. user2 pass2 2
  21. etc.
  22.  
  23. 1.) Retrieve all rows and display it in a table
  24. */
  25. $query = "select * from user_table order by Username";
  26. $result = pg_query($conn,$query);
  27. if (!$result) {
  28. // Error on Query
  29. // Your Error code Here
  30. } else {
  31. numrows = pg_numrows($result);
  32. echo "<table>";
  33. for ($i=0; $i < $numrows ; $i++) {
  34. $DataArr = pg_fetch_rows($result,$i);
  35. echo "<tr><td>$DataArr[0]</td><td>$DataArr[1</td><td>$DataArr [2]<td></tr>";
  36. } // For
  37. echo "</table>";
  38. } // Query
  39. } // Connection
  40. pg_close($conn);
  41. ?>
  42.  
  43.  
Comments on this Code Snippet
May 23rd, 2006
0

Re: Accessing PostgreSQL Database from PHP

I'm sure the code is good, but I recommend the use of the popular ADOdb class library for database access. It is fast and robust and allows you to use the same code to connect to multiple databases as needed.
http://adodb.sourceforge.net/
Posting Whiz
Troy is offline Offline
354 posts
since Jun 2005
Message:
Previous Thread in PHP Forum Timeline: replace address - how to?
Next Thread in PHP Forum Timeline: concert decimal to integer





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC