Search through all the fields of DB table
Posted: Thu Nov 25, 2010 1:00 am
Hy!
I've done a search engine, that works only if I search partly (by name or surname), but if I want to search through both fields at the same time (all), it's not working. Here's my code:
<h2>Searching</h2>
<form name="search" method="post" action="<?php $_PHP_SELF ?>">
Search: <input name="find" id="find" type="text"/> in:
<select name="field" id="field">
<option value="all">all</option> // this would be the option to search through both fields
<option value="name">name</option>
<option value="surname">surname</option>
</select>
<input type="submit" name="search" value="Search" />
</form>
Thanks for helping me out!
I've done a search engine, that works only if I search partly (by name or surname), but if I want to search through both fields at the same time (all), it's not working. Here's my code:
<h2>Searching</h2>
<form name="search" method="post" action="<?php $_PHP_SELF ?>">
Search: <input name="find" id="find" type="text"/> in:
<select name="field" id="field">
<option value="all">all</option> // this would be the option to search through both fields
<option value="name">name</option>
<option value="surname">surname</option>
</select>
<input type="submit" name="search" value="Search" />
</form>
Code: Select all
if(isset($_POST['search'])) {
echo "<h2>Results:</h2><p><hr>";
$find = $_POST['find'];
$field = $_POST['field'];
if ($find == "") {
echo "<p>No results!</p>";
exit;
}
$dbhost = 'host';
$dbuser = 'myuser';
$dbpass = 'mypassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$find = strip_tags($find);
$find = trim($find);
mysql_select_db('mydb');
$data = mysql_query("SELECT * FROM users WHERE $field LIKE'%$find%'");
// this is not working: $data2 = mysql_query("SELECT * FROM users WHERE $name LIKE'%$find%' || $surname LIKE'%$find%'");
$i=0;
while($result = mysql_fetch_array($data)) {
echo "Name: " . $result['name'] . " <br>";
echo "Surname: " . $result['surname'] . " <br>";
echo "<hr>";
$i++;
}
}