How do I search a database using a specific field search? This code also needs to be secured from SQL injection but here is the basic code for learning purposes. The database connects but doesn't show the data. Please help!
Here is the html input form.
<h2>Search</h2>
<form name="search" action="searchresults.php" method="POST">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="firstName">First Name</option>
<Option VALUE="lastName">Last Name</option>
<Option VALUE="email">email</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
Here is the basic connection and table output. some of the code may be missing.
<?php
mysql_connect("127.0.0.1", "root", "pass") or die(mysql_error()) ;
mysql_select_db("users") or die(mysql_error()) ;
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$email=$_POST['email'];
$find=$_POST['find'];
$field=$_POST['field'];
$data="SELECT firstName, lastName, email FROM userInfo WHERE upper($field) LIKE '% $find%'";
$result = mysql_query($data);
$count=mysql_numrows($result);
if($count > 0){
echo '<table align="center" width="800" border="0" cellpadding="4">';
echo '<tr height = 200><td>';
echo "<h1><font size='4' color='red'>Search Results</h1></font>";
echo "<table>";
echo "<table border='0' width='750' align='center'>";
echo "
<td width='30%' align='center'>First Name</td>
<td width='30%' align='center'>Last Name</td>
<td width='40%' align='center'>Email</td>";
echo "</tr>";
$row_number = 1;
while ($row = mysql_fetch_array($data)) {
$id= $row["id"];
$firstName= $row["firstName"];
$lastName= $row["lastName"];
$email= $row["email"];
for ($i=0; $i<3; $i++) {
echo"<td><font size =\"4\" color=\"black\"> $row[$i]</td>";
}
echo"</tr>";
$row_number++;
}
echo "</table>";
echo '</td></tr>';
echo '</table>';
}
?>
$data="SELECT firstName, lastName, email FROM userInfo WHERE upper($field) LIKE '% $find%'";
That space LIKE '% $find%'";
probably isn't correct
This is because upper($field)
returns string, not the column-name that you might expect. Sql is built like 'FIRSTNAME'(as string) LIKE '% BOB%'
, which is false (because string 'FIRSTNAME' does not contain ' BOB'.
And one more problem, two spaces included before $find, even when user try to find 'BOB', db does not find 'BOB' because it does not includes two space before BOB.
To make this work, you have to prepare column name outside of sql world like below:
$searchField = strtoupper($field);
$data="SELECT firstName, lastName, email FROM userInfo WHERE `$searchField` LIKE '%$find%'";
Note that field name cannot be parameterized using prepare statement AFAIK so you have to do much care of it.