Accessing PostgreSQL Database from PHP

JRED JRED is offline Offline Apr 20th, 2005, 3:06 am |
0
This code snippet will attempt to show newbies to php how to connect and retrieve data from a PostgreSQL Database Server using PHP.
Quick reply to this message  
PHP Syntax
  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.  
0
Troy Troy is offline Offline | May 23rd, 2006
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/
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC