I am trying to get input from user, then when he press submit, it will do a query in a database and return the results in a table. My code however doesn't seem to wait, as it automatically executes the scenario where my var that holds the result of query is false. I am trying to do this on same page, as it worked if I send the data to another page, but I want to minimize the number of files I'm using.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>View a Faculty Member</title>
<style type="text/css">
.block {
display:block;
margin-top:3px;
}
</style>
</head>
<body>
<h1>View a faculty member:</h1>
<form action="" method="post">
<label class="block">Please Enter ID: <input type="text" placeholder="ie. 12345" maxlength="30" size="30" name="id"></label>
<input class="block" type="submit" name="submit" value="Get Faculty Member">
</form>
<hr/>
<?php
// 1- get the id
// 2- construct query in string
// 3- connect to db
// 4- execute the query
// 5- put the result in a var
// 6- get the information from the var into a table
$id = $_POST["id"]; // step 1
$query = "SELECT * FROM FM WHERE id=\"$id\""; // step 2
try {
$db = new PDO("mysql:dbname=project;host=localhost", "khaled", ""); // step 3
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$row = $db->query($query)->fetch(); // step 4 & step 5
if ($row == FALSE) {
// id doesnt exist since the query failed
?>
<h3>The ID you entered does not exist.</h3>
<h4>Please try again.</h4>
<?
} else {
// step 6
displayTable($row);
}
} catch (PDOException $ex) {
?>
<h3 style="color:red;">An error occured.</h3>
<p>An error occured during the connection to the database.</p>
<p>Exact error message: <?= $ex->getMessage() ?></p>
<?php
}
function displayTable ($row) {
?>
<table border="1">
<tr>
<th>ID</th>
<th>Last Name</th>
<th>First Name</th>
<th>Office</th>
<th>Extension</th>
<th>Home Phone</th>
<th>Mobile Phone</th>
<th>Address</th>
<th>Email</th>
<th>Starting Year</th>
<th>Termination Year</th>
<th>Latest Degree</th>
<th>Obtained From</th>
<th>Degree Year</th>
<th>Research Interest</th>
</tr>
<tr>
<td><?= $row["id"] ?></td>
<td><?= $row["lastName"] ?></td>
<td><?= $row["firstName"] ?></td>
<td><?= $row["office"] ?></td>
<td><?= $row["extension"] ?></td>
<td><?= $row["homePhone"] ?></td>
<td><?= $row["mobilePhone"] ?></td>
<td><?= $row["address"] ?></td>
<td><?= $row["email"] ?></td>
<td><?= $row["startingYear"] ?></td>
<td><?= $row["terminationYear"] ?></td>
<td><?= $row["latestDegree"] ?></td>
<td><?= $row["obtainedFrom"] ?></td>
<td><?= $row["degreeYear"] ?></td>
<td><?= $row["researchInterest"] ?></td>
</tr>
</table>
<?php
}
?>
</body>
</html>
How can I make my code wait for user to enter input then to check if it is false query or not?