I have five textboxes which are associated with its own field from the my sql database. What I want to do is fetch data from the mysql database depending on what the user has entered in the text box. The problem is that if a text box is empty, it outputs no record as that the textbox is trying to post ” as a piece of data. How can I implement it so that if a textbox is empty, it will look for all (or any data) in that field. E.g if SessionID textbox is empty, then select all sessionID’s. Below is my current coding:
<body>
<form action="exam_interface.php" method="post" name="sessionform"> <!-- This will post the form to its own page"-->
<p>Session ID: <input type="text" name="sessionid" /></p> <!-- Enter Session Id here-->
<p>Module Number: <input type="text" name="moduleid" /></p> <!-- Enter Module Id here-->
<p>Teacher Username: <input type="text" name="teacherid" /></p> <!-- Enter Teacher here-->
<p>Student Username: <input type="text" name="studentid" /></p> <!-- Enter User Id here-->
<p>Grade: <input type="text" name="grade" /></p> <!-- Enter Grade here-->
<p><input type="submit" value="Submit" /></p>
</form>
<?php
$username="u0867587";
$password="31may90";
$database="mobile_app";
$sessionid = $_POST['sessionid'];
$moduleid = $_POST['moduleid'];
$teacherid = $_POST['teacherid'];
$studentid = $_POST['studentid'];
$grade = $_POST['grade'];
mysql_connect('localhost',$username,$password);
@mysql_select_db($database) or die("Unable to select database");
$result = mysql_query("SELECT * FROM Module m INNER JOIN Session s ON m.ModuleId = s.ModuleId JOIN Grade_Report gr ON s.SessionId = gr.SessionId JOIN Student st ON gr.StudentId = st.StudentId WHERE gr.SessionId = '$sessionid' AND m.ModuleId = '$moduleid' AND s.TeacherId = '$teacherid' AND gr.StudentId = '$studentid' AND gr.Grade = '$grade'");
$num=mysql_numrows($result);
echo "<table border='1'>
<tr>
<th>Student Id</th>
<th>Forename</th>
<th>Session Id</th>
<th>Grade</th>
<th>Mark</th>
<th>Module</th>
<th>Teacher</th>
</tr>";
while ($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['StudentId'] . "</td>";
echo "<td>" . $row['Forename'] . "</td>";
echo "<td>" . $row['SessionId'] . "</td>";
echo "<td>" . $row['Grade'] . "</td>";
echo "<td>" . $row['Mark'] . "</td>";
echo "<td>" . $row['ModuleName'] . "</td>";
echo "<td>" . $row['TeacherId'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
Thank You
The simplest way would be to build the WHERE part of the query dynamically based on what has been submitted, this way if the field in question is empty, that part of the where statement wouldn’t exist.
Take this example, that has two possible inputs $_POST[‘foo’] and $_POST[‘bar’]: