I need some help on how to set up this page. Let’s say I have a mysql table of 5 or so fields of data (i.e. id, firstname, lastname, favorite color, favorite number). I would like to give the user the ability to search the table, so I create a “Search” page.
On the page, I’ll have text fields for ID, lastname and firstname. From here the user would insert data to search by. I guess what I’m confused about is how I can write a script that takes in different search criteria from the text fields and ignore the fields that are left blank. For example, if a user only puts in a first or last name, then all the entries with that same first/last name will be shown. If they only insert the id (would be unique), then all the content for that user will be shown. If they put in both a last name and a last name, then all the data for entries having that first and last name will appear.
I suppose this is basic but I’m new to this so any help on how to set this up would be greatly appreciated.
Code Update:
<?php
//Connect and select database
//if user wants to search
if(isset($_POST['submit']))
{
$sqlConditions = array();
if(isset($_POST['id'])){
$id = filter_var($_POST['id'], FILTER_VALIDATE_INT);
$sqlConditions[] = 'id = ' . $id;
} else {
$id = 0;
}
if(isset($_POST['firstname'])){
$firstName = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'firstname = ' . $firstName;
} else {
$firstName = '';
}
if(isset($_POST['lastname'])){
$lastName = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'lastname = ' . $lastName;
} else {
$lastName = '';
}
$query = 'SELECT * FROM students WHERE ' . join (' AND ', $sqlConditions);
//print query
while ($row = $query->fetch_row())
{
print "LastName = " . $row[0] . " FirstName = " . $row[1].
"Favorite Color = " . $row[2] . " Favorite Number = " . $row[3] . "<br /><br />\n";
}
}
?>
<html>
<body>
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<p>ID:<input type = "id" id="id" name="id" size="20" maxlength="40" /></p>
<p>First Name:<input type = "firstname" id="firstname" name="firstname" size="20" maxlength="40" /></p>
<p>Last Name:<input type = "lastname" id="lastname" name="lastname" size="20" maxlength="40" /></p>
<input type="submit" id="submit" name ="submit" value="Search" />
</form>
</body>
</html>
You may try the following approach:
Step 1: get data from POST, validate it and compose the future sql conditions
Step 2: Compose the query
Of course you will need to use mysql_real_escape_string or some modern approach as PDO to make sure you avoid SQL injection.