How Do You Prepopulate Text Fields in a Web Page with Values from a SQL Database?

Problem scenario
You have a web page from an .php file that includes HTML code.  There are fields visible in the web page to the user.  These fields accept text. You want the fields to not be blank; you want the fields to have suggested values of text in them. You want the data in the fields to be taken from the result of a SQL statement.  How do you prepopulate text fields in a LAPP web page with values from SQL statements?

Solution
This assumes have you set up the LAPP stack.  If you do not know how to implement front-end authentication for your LAPP instance, you may want to see one of two blog posts.  This solution assumes you have configured authentication variables that you see in the pg_connect() statement.

Here is an example PHP web page (.php file) that will prepopulate text fields that the user may modify from his/her web browser:

<?php

   $db = pg_connect( "$host $port $dbname $credentials"  );

//The above line assumes the $host, $port, $dbname, and $credentials variables were properly assigned.

//With PHP code compose SQL statements like this:

   $query = 'select col1 from ' . $tn . ' where continual_col = ' . $id . ';';

// This assumes that col1 exists in the table defined in the variable $tn.
// This assumes that $id is the value of exactly one row in the table defined with variable $tn.
// This query will retrieve the value of one field in a table in the database.

//Now invoke Postgres commands via PHP to process the results of the query:

   $selectval = pg_query($query);
   $row1 = pg_fetch_row($selectval);
   $finalval = current($row1);

?>

<html>
<body>

<form action="nextpage.php" method="post">

good_field: <input type="text" name="suggestedval" value="<?php echo $finalval; ?>">

<input type="submit">
</form>

</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *