Wednesday, September 24, 2014

PHP - Connecting to PSQL from PHP

Quick post on how to connect to PSQL from PHP, run queries, and retrieve results. You can use the same syntax for inserts, updates and other statements.

linux-test# vim test.php


You can add the following lines to the php file just created to retrieve and loop through the results.

//Create the query variable
 $current_pg_query = "select column1, column2, column3 from testtable";  

//Send the query to the database connection made earlier in the script
 $current_pg_query_result = pg_query($connection,$current_pg_query);  

//Use a while loop to fetch the row
 while ($row = pg_fetch_row($current_pg_query_result)) {  

//loop through each field in the row. In this example you will have 3 fields (column1, column2, column3) in each row. 
   foreach ($row as $values) {   
    echo "$value";   
   }  
 }  

Many more articles to come so ....

Please subscribe/comment/+1 if you like my posts as it keeps me motivated to write more and spread the knowledge.

No comments:

Post a Comment