Accessing PostgreSQL Database from PHP


  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. 1.) Retrieve all rows and display it in a table
  23. */
  24. $query = "select * from user_table order by Username";
  25. $result = pg_query($conn,$query);
  26. if (!$result) {
  27. // Error on Query
  28. // Your Error code Here
  29. } else {
  30. numrows = pg_numrows($result);
  31. echo "<table>";
  32. for ($i=0; $i < $numrows ; $i++) {
  33. $DataArr = pg_fetch_rows($result,$i);
  34. echo "<tr><td>$DataArr[0]</td><td>$DataArr[1</td><td>$DataArr [2]<td></tr>";
  35. } // For
  36. echo "</table>";
  37. } // Query
  38. } // Connection
  39. pg_close($conn);
  40. ?>

0 comments: