Javascript Parameter: PHP Database Query Sample

Arclab® Web Form Builder

Sample: Passing Values from a PHP Database Query

In the following example, the input fields for first name and last name are to be filled with values from a database query. The result of the data record with ID=15 should be used here. Please note that the ID=15 is just an example. Which data set should be used must be known and cannot be a value from the form, since the SQL query takes place on the server side and only the result of the query is passed to the form. A typical area of application for this scenario would be a CMS or other user system in which the user ID is determined by the logged in user.

 

First add the input fields to your form.
You can also use hidden fields instead, if the user should not be able to edit the values.

 

PHP DB Sample Form

 

The form now contains 2 fields: {First_Name} and {Last_Name}.
We now have to establish the connection from the form fields to the Javascript variables.

 

The form element "Javascript Parameter" (in "External Data") is used for this.

 

Connect Field to Javascript variable

 

Insert two "Javascript Parameter":
fname for: {First_Name}
lname for: {Last_Name}

 

The form should now look like this:
(The position of the "Javascript Parameter" does not matter here)

 

Form with Javascript Parameters

 

Now the result of the PHP database query has to be transferred to the Javascript variables.
To do this, edit the PHP host page that executes the database query.

 

The transfer can be done using a simple PHP echo statement:
Important! This PHP code must be inserted into the host page. Do not add this code as "Custom PHP Code" to "Email and Database"!

...
<?php
...
// query database (basic sample code without error checking!)

$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM Sample WHERE id=15";
$result = mysqli_query($conn, $sql);
// the query result should be a single row!
$row = mysqli_fetch_assoc($result);
...
// database query result is in $row
// use temporary PHP variables ($firstname and $lastname) to avoid a "quote" error in the echo statement

$firstname = $row["FirstName"];
$lastname = $row["LastName"];
...
// assign the query result to the javascript variables
echo "<script>var fname='$firstname'; var lname='$lastname';</script>";
...
?>
...

 

The result of the PHP database query is first transferred to the Javascript variables using the "echo" statement. The Javascript variables are linked to the form fields via the "Javascript Parameter" form element. If you now open the host page, the PHP database query is executed and the fields are filled with the values from the database.