I am trying to create a query where a user can enter: first name, last name, nick name, grade, and gender. However, some of these fields may be empty.
I know how to create a query that will check all of those. However, how can I make it where it won’t query for something if it’s not given. For example, a user might want to search by last name and gender, but not the others.
How can I go about doing this? Thanks so much for the help!
@Ibu, this is what I have so far:
// Now we need to query the database for these terms
$sql_query = "SELECT * FROM `students` WHERE `first_name` = '" . $first_name . "' AND `last_name` = '" . $last_name . "' AND `nick_name` = '" . $nick_name . "' AND `grade` = '" . $grade . "' AND `gender` = '" . $gender . "'";
$result = mysql_query($sql_query);
// Let's check to make sure there is an actual result
$num_rows = mysql_num_rows($result);
if($num_rows < 1) {
echo 'No student was found using that criteria.';
}
if($num_rows >= 1) {
echo '<p>' . $num_rows . ' result(s) found. Below are the results:</p>';
echo '<br />';
}
while($row = mysql_fetch_array($result)) {
echo '
<table border="1" width="400">
<tr>
<td colspan="2" align="center">Student Profile - ' . $row['last_name'] . ', ' . $row['first_name'] . '</td>
</tr>
<tr>
<td>First Name: </td>
<td>' . $row['first_name'] . '</td>
</tr>
<tr>
<td>Last Name: </td>
<td>' . $row['last_name'] . '</td>
</tr>
<tr>
<td>Nick Name: </td>
<td>' . $row['nick_name'] . '</td>
</tr>
<tr>
<td>Grade: </td>
<td>' . $row['grade'] . '</td>
</tr>
<tr>
<td>Gender: </td>
<td>' . $row['gender'] . '</td>
</tr>
</table> <br /><br />';
}
Just check the
$_POSTvars and build the query on that.Like this for example (this bad in that it does not sanitize the
$_POSTfor injection, but its a good start):Then just append the
$wherevariable to the end of your query