Friday, October 18, 2013

SQL Query Form Design Pattern Using "pg" driver

The following is a PHP Script that can serve as a design pattern for HTML form handling with "pg" connection driver for the PostgreSQL database.


<html>
<head>
<title>Postgresql pg Query Interface</title>
<!--
Clement L. Rasul
copyright (c) 2013
-->
</head>
<body>

<?php
$sql = trim($_POST['sql']);
$host = "localhost";
$user = "postgres";
$pw = "wordpass123";
$db = "testdb";

# Query Form
echo "<h1>PostgreSQL pg Query Interface</h1>";
echo "<form action='postgresql_pg_query.php' method='post'><textarea cols='80' rows='5' name='sql'>";
echo "$sql";
echo "</textarea><br /><input type='submit'></form>";

# Connection Check
$con = pg_connect("host=$host port=5432 dbname=$db user=$user password=$pw") or 
  die ("Database Status: <font color='red'><blink><b>Connection Error!</b></blink></font>"); echo "Database Status: <font color='green'><blink><b>Connected...</b></blink></font><hr />"; # SQL Query Script $result = pg_query($con, $sql); $num_rows = pg_num_rows($result); $num_cols = pg_num_fields($result); echo "Rows: ".$num_rows."<br />"; echo "Columns: ".$num_cols."<hr />"; echo "<table border='1'>"; # Table Heading $f=0; while ( $col = pg_field_name($result, $f) ) { $fn = $col; echo "<th>".$fn."</th>"; $f=$f+1; } # Table Content while ( $row = pg_fetch_array($result) ) { echo "<tr>"; $c = 0; while ( $c < $num_cols ) { echo "<td>".$row[$c]."   </td.>"; $c = $c+1; } echo "</tr>"; } echo "</table>"; ?> </body> </html>

No comments: