Search through all the fields of DB table

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ursl40
Forum Commoner
Posts: 37
Joined: Thu Nov 18, 2010 5:01 am

Search through all the fields of DB table

Post by ursl40 »

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>

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++;
	}
 }
Thanks for helping me out!
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Search through all the fields of DB table

Post by social_experiment »

The following syntax seems to work SELECT *FROM tag_tbl WHERE tag LIKE 'gprs' OR post_id LIKE 'gprs' (Substitute your values / fields).
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply