Edward Hammock Edward Hammock - 3 years ago 159
PHP Question

Pre Complete HTML Form with PHP and MYSQL

I am creating a simple page which updates a single record

tempKey=1
, single field
reqdTemp
MySQL dBase. I have the form working fine; it updates the record, then returns to the initial form ready for the user to change the temperature again.

Q: I would like the form to be pre-populated with the existing information from the database so the user sees the current required temperature about to be changed. I'm not sure where to start!!

The form,
updateTemperature.php
, is this:

<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>


The post script,
insert.php
is this:

<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';

$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);

echo "1 record added";
header ('location: PiBQ_Temp2.php');

mysql_close($con)
?>

Answer Source

To pre-populate the form, query the database for the current value and set that in the returned HTML. So your updateTemperature.php could become something like this:

<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
echo 'Connected successfully';

$currentTemp = 100; // some default
$sql = "SELECT reqdTemp FROM PiBQ_Temp WHERE tempKey = 1";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) > 0) {
  $row = mysqli_fetch_assoc($result);
  $currentTemp = $row['reqdTemp'];
}

mysql_close($con);
?>
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" value="<?= $currentTemp ?>" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download