Demiën Drost Demiën Drost - 4 months ago 33
PHP Question

Form and PHP result display on same page

I have a form on one page linking to a PHP file (action), now the PHP result is being displayed in this PHP file/page. But I want the result to be displayed on the page with the form. I have searched thoroughly and couldn't find it anywhere. Perhaps any of you can help?

Code: /citizens.php (main page)

<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>


Code: /infoct.php

<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/citizens.php" /> -->
</head>

<body>

<?php {
$ID2 = isset($_POST['ID']) ? $_POST['ID'] : false;
}

$connect = mysql_connect('localhost', 'root', 'passwd');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);

?>
</body>
</html>


My fixed code thanks to Marc B



<form method="post">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ID = isset($_POST['ID']) ? $_POST['ID'] : false;

$connect = mysql_connect('fdb13.biz.nf:3306', '1858208_inhabit', '12345demien12345');
mysql_select_db ('1858208_inhabit');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID";
$res = mysql_query($sql);
if ($ID > 0) {
echo "<p><b>Citizen Identification number is</b> </p>";

while($row = mysql_fetch_array($res))
echo "<br><p><b>Surname: </b></b></b>", $row['Surname'], "</p>";
echo "<br><p><b>First Name: </b></b>", $row['Name'], "</p>";
echo "<br><p><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p>";
echo "<br><p><b>Address: </b></b></b></b></b>", $row['Address'], "</p>";
echo "<br><p><b>Background information: </b><br>", $row['RPS'], "</p>";

mysql_close ($connect);
}
else {
echo "<p>Enter a citizen ID above</p>";
}
}
?>


Database snap
DB Snap

Answer

A single-page form+submit handler is pretty basic:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
 ... form was submitted, process it ...
 ... display results ...
 ... whatever else ...
}
?>

<html>
<body>
<form method="post"> ... </form>
</body>
</html>

That's really all there is.