deeejay

PostgreSQL - Use PHP to Output Data in JSON Format (2)

Jun 14th, 2016
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.51 KB | None | 0 0
  1. Create pg.query.inc.php
  2. ===
  3. <?php
  4. $connectString = 'host=db_host.org port=5432 dbname=db_name user=your_username password=your_password';
  5. $link = pg_connect($connectString);
  6.  
  7. if (!$link) {
  8.     echo "error";
  9. } else {
  10.  
  11. $result = pg_query($link, $sql);
  12. $rows = array();
  13. while($r = pg_fetch_assoc($result)) {
  14.     $rows[] = $r;
  15. }
  16. print json_encode($rows);
  17. }
  18. ?>
  19.  
  20. Create php file and pass in db connection
  21. ===
  22. <?php
  23. $sql = "SELECT id, first_name, last_name FROM person";
  24.  
  25. include 'pg.query.inc.php';
  26. ?>
Advertisement
Add Comment
Please, Sign In to add comment