Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Php / mysql search problem

Featured Replies

Hi All

 

Im working on a search function from a tutorial but running into a few problems.

 

When I do a search for 'ben' which is in my db in 'fname' nothing happens? I want to be able to display that record with 'ben' in?

 

Hope this makes sense?

 

But if a do a search for france which is in 'email' I get this:

 

Title:

Score:1.0 Date: 01/01/70

 

I would also like to display that record details?

 

Heres the code:

 

 

Thanks

 

 

Code:

 

<?php  
// Full-Text Search Example  
/************************** change to match your connection method ********************/  

require_once ('../mysql_connect.php'); // Connect to the db.  


// Create the search function:  

function searchForm()  
{  
 // Re-usable form  

 // variable setup for the form.  
 $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');  
 $normal = (($_GET['mode'] == 'normal') ? ' selected="selected"' : '' );  
 $boolean = (($_GET['mode'] == 'boolean') ? ' selected="selected"' : '' );  

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';  
 echo '<input type="hidden" name="cmd" value="search" />';  
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';  
 echo 'Mode: ';  
 echo '<select name="mode">';  
 echo '<option value="normal"'.$normal.'>Normal</option>';  
 echo '<option value="boolean"'.$boolean.'>Boolean</option>';  
 echo '</select> ';  
 echo '<input type="submit" value="Search" />';  
 echo '</form>';  
}  


// Create the navigation switch  
$cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');  

switch($cmd)  
{  
 default:  
echo '<h1>Search Database!</h1>';  
searchForm();  

 break;  


 case "search":  
searchForm();  
echo '<h3>Search Results:</h3><br />';  

$searchstring = mysql_escape_string($_GET['words']);  
switch($_GET['mode'])  
{  
  case "normal":  
	$sql = "SELECT user_id, fname, lname, details, age, location, email,  
		   MATCH(user_id, fname, lname, details, age, location, email)  
		   AGAINST ('$searchstring') AS score FROM users  
		   WHERE MATCH(user_id, fname, lname, details, age, location, email)  
		   AGAINST ('$searchstring') ORDER BY score DESC";  
  break;  

  case "boolean":  
	$sql = "SELECT user_id, fname, lname, details, age, location, email,  
		   MATCH(user_id, fname, lname, details, age, location, email)  
		   AGAINST ('$searchstring' IN BOOLEAN MODE) AS score FROM users  
		   WHERE MATCH(user_id, fname, lname, details, age, location, email)  
		   AGAINST ('$searchstring' IN BOOLEAN MODE) ORDER BY score DESC";  
  break;  
}  

// echo $sql;  

$result = mysql_query($sql) or die (mysql_error());  

while($row = mysql_fetch_object($result))  
{  
  echo '<strong>Title: '.stripslashes(htmlspecialchars($row->mytable_title)).'</strong><br />';  
  echo 'Score:'. number_format($row->score, 1).' Date: '.date('m/d/y', $row->mytable_dts).'<br />';  
  echo '<p>'.stripslashes(htmlspecialchars($row->mytable_caption)).'</p>';  
  echo '<hr size="1" />';  
}  
 break;  
}  
?>  

</body>  
</html>

have you thought about using the mysql like command? say you are looking for a field in the database that contains the word FINDME you would use this sql

 

$word = 'FINDME';
$sql = "SELECT * FROM mytable WHERE myfield LIKE '%{$word}%'";

 

Sure you can fit that into your code. see if it works better than match

It would be better for your server to be more specific in your searches.

 

You are using a tank to open a walnut here ;)

 

If you do various tests on the search input to guess waht the user is after BEFORE submitting it to the mysql query, you will get more accurate results and faster too.

  • Author

thanks guys I now know what you mean!

 

I used $sql = "SELECT * FROM users WHERE fname LIKE '%{$searchstring}%'";

 

searches the first name, is there any way to all field names?

 

Ive tried $sql = "SELECT * FROM users WHERE fname, lname, details, age, location, email LIKE '%{$searchstring}%'";

 

but get this message:

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' lname, details, age, location, email LIKE '%name%'' at line 1

no you'll have to do them one at a time like this

 

$sql = "SELECT * FROM users WHERE fname LIKE '%{$searchstring}%' OR  lname LIKE '%{$searchstring}%' OR  details LIKE '%{$searchstring}%' OR  age LIKE '%{$searchstring}%' OR  location LIKE '%{$searchstring}%' OR email LIKE '%{$searchstring}%'";

 

Still that seems pretty big. Does the search really have to go through it all? It could be better to have a drop down menu of fields so the person can focus the search

you are seemingly lacking context here.

 

The fname, lname, and details will all be string searches without an @ in them,

the age search will be a number (or related keyword eg seventeen)

the email will be a string search with an @ in there somewhere.

Add Reply

do a strstr and is_numeric on the query to try and break it up a bit.

you might only be searching for half an email so no @ but something is needed to split it up. searching every when it's not needed is extreme

  • Author

Thanks for the tips, Ive added a drop down function and only one search type...

 

<?php
// Full-Text Search Example
/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 



// create variables for the db 
	 $firstn='fname'; 
	 $lastn='lname'; 
	 $details='details'; 
	 $age='age'; 
	 $location='location'; 
	 $email='email'; 

// Create the search function:

function searchForm()
{
 // Re-usable form

 // variable setup for the form.
 $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');
 $normal = (($_GET['mode'] == 'normal') ? ' selected="selected"' : '' );
 $searchby = !isset($_GET['searchby'])? NULL : $_GET['searchby']; 	 

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in ';
 echo '<select name="searchby">';
 echo '<option value="fname"'.$firstn.'>First Name</option>';
 echo '<option value="lname"'.$lastn.'>Last Name</option>';
 echo '<option value="details"'.$details.'>Details</option>';
 echo '<option value="age"'.$age.'>Age</option>';
 echo '<option value="location"'.$location.'>Location</option>';
 echo '<option value="email"'.$email.'>Email</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}


// Create the navigation switch
$cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');

switch($cmd)
{
 default:
echo '<h1>Search Database!</h1>';
searchForm();

 break;


 case "search":
searchForm();
echo '<h3>Search Results:</h3><br />';

$searchstring = mysql_escape_string($_GET['words']);
switch($_GET['normal'])
{
  case "normal":
	 $sql = "SELECT * FROM users WHERE $searchby LIKE '%{$searchstring}%'";
  break;

} 

// echo $sql;

$result = mysql_query($sql) or die (mysql_error());


while($myrow = mysql_fetch_object($result))
{

  echo '<hr size="1" />';
  echo '<table align="center" cellspacing="0" cellpadding="5">';
  echo'<td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .' </span></td>';  
  echo '</tr>'; 
  echo '</table>'; 
}
 break;
}
?>

</body>
</html>

 

For some reason I cant get it to display records with "seach term" in?

 

Also php_penguins comment ' do a strstr and is_numeric on the query to try and break it up a bit.' where would I add that?

 

Thanks for your help! :D

Thanks for the tips, Ive added a drop down function and only one search type...

 

<?php
// Full-Text Search Example
/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 



// create variables for the db 
         $firstn='fname'; 
         $lastn='lname'; 
         $details='details'; 
         $age='age'; 
         $location='location'; 
         $email='email'; 

// Create the search function:

function searchForm()
{
  // Re-usable form
  
  // variable setup for the form.
  $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');
  $normal = (($_GET['mode'] == 'normal') ? ' selected="selected"' : '' );
  $searchby = !isset($_GET['searchby'])? NULL : $_GET['searchby'];      
  
  echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
  echo '<input type="hidden" name="cmd" value="search" />';
  echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
  echo 'in ';
  echo '<select name="searchby">';
  echo '<option value="fname"'.$firstn.'>First Name</option>';
  echo '<option value="lname"'.$lastn.'>Last Name</option>';
  echo '<option value="details"'.$details.'>Details</option>';
  echo '<option value="age"'.$age.'>Age</option>';
  echo '<option value="location"'.$location.'>Location</option>';
  echo '<option value="email"'.$email.'>Email</option>';
  echo '</select> ';
  echo '<input type="submit" value="Search" />';
  echo '</form>';
}


// Create the navigation switch
$cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');

switch($cmd)
{
  default:
    echo '<h1>Search Database!</h1>';
    searchForm();
  
  break;
  
  
  case "search":
    searchForm();
    echo '<h3>Search Results:</h3><br />';
    
    $searchstring = mysql_escape_string($_GET['words']);
    switch($_GET['normal'])
    {
      case "normal":
         $sql = "SELECT * FROM users WHERE $searchby LIKE '%{$searchstring}%'";
      break;
      
    } 
    
    // echo $sql;
    
    $result = mysql_query($sql) or die (mysql_error());
    
    
    while($myrow = mysql_fetch_object($result))
    {
      
      echo '<hr size="1" />';
      echo '<table align="center" cellspacing="0" cellpadding="5">';
      echo'<td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .' </span></td>';  
      echo '</tr>'; 
      echo '</table>'; 
    }
  break;
}
?>

</body>
</html>

 

For some reason I cant get it to display records with "seach term" in?

 

Also php_penguins comment ' do a strstr and is_numeric on the query to try and break it up a bit.' where would I add that?

 

Thanks for your help! :D

 

the is_numeric was a way to automate the search without the drop. like if it's a number then you search age not first name. I'm not sure what your problem is. can you describe it better or supply a url/screen shot?

  • Author
the is_numeric was a way to automate the search without the drop. like if it's a number then you search age not first name. I'm not sure what your problem is. can you describe it better or supply a url/screen shot?

 

Thanks for the speedy reply

 

Heres the url...

 

http://www.ben-smith.net/cms_example/site/search2.php

 

I have ben in the field 'fname', so when I do a search for ben in firstname I want all the records with ben as a first name to appear and so on for the other fields.

 

But all i get at the moment is Query was empty?

 

Hope this helps, thanks Ben

  • Author

Hi All,

 

The were a few errors on that script which ive hopefull sorted!

 

heres the new code:

 

<?php
// Full-Text Search Example
/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 



// create variables for the db 
$firstn='fname'; 
$lastn='lname'; 
$details='details'; 
$age='age'; 
$location='location'; 
$email='email'; 

// Create the search function:

function searchForm()
{
 // Re-usable form

 // variable setup for the form.
 $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');
 $searchby = (isset($_GET['searchby'])? NULL : $_GET['searchby']); 	 

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in';
 echo '<select name="searchby">';
 echo '<option value="fname"'.$firstn.'>First Name</option>';
 echo '<option value="lname"'.$lastn.'>Last Name</option>';
 echo '<option value="details"'.$details.'>Details</option>';
 echo '<option value="age"'.$age.'>Age</option>';
 echo '<option value="location"'.$location.'>Location</option>';
 echo '<option value="email"'.$email.'>Email</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}


// Create the navigation switch
$cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');

switch($cmd)
{
 default:
echo '<h1>Search Database!</h1>';
searchForm();

 break;


 case "search":
searchForm();
echo '<h3>Search Results:</h3><br />';

$searchstring = mysql_escape_string($_GET['words']);

$sql = "SELECT * FROM users WHERE $searchby LIKE '%{$searchstring}%'";

break;

} 

// echo $sql;

$result = mysql_query($sql) or die (mysql_error());


while($myrow = mysql_fetch_object($result))
{

  echo '<hr size="1" />';
  echo '<table align="center" cellspacing="0" cellpadding="5">';
  echo'<td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .' </span></td>';  
  echo '</tr>'; 
  echo '</table>'; 
}
 break;

?>

</body>
</html>

 

 

http://www.ben-smith.net/cms_example/site/search3.php

 

 

I get this message straight away without pressing any buttons:

 

Query was empty

 

 

But when I do a search, I get this:

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIKE '%ben%'' at line 1

 

im running mysql 5.0.26????

I've made some changes.

 

<?php
// Full-Text Search Example
/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 



// create variables for the db 
$firstn='fname'; 
$lastn='lname'; 
$details='details'; 
$age='age'; 
$location='location'; 
$email='email'; 

// Create the search function:

function searchForm()
{
  // Re-usable form
  
  // variable setup for the form.
  $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');
  $searchby = (isset($_GET['searchby'])? NULL : $_GET['searchby']);      
  
  echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
  echo '<input type="hidden" name="cmd" value="search" />';
  echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
  echo 'in';
  echo '<select name="searchby">';
  echo '<option value="fname"'.$firstn.'>First Name</option>';
  echo '<option value="lname"'.$lastn.'>Last Name</option>';
  echo '<option value="details"'.$details.'>Details</option>';
  echo '<option value="age"'.$age.'>Age</option>';
  echo '<option value="location"'.$location.'>Location</option>';
  echo '<option value="email"'.$email.'>Email</option>';
  echo '</select> ';
  echo '<input type="submit" value="Search" />';
  echo '</form>';
}


// Create the navigation switch
$cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');

switch($cmd)
{
  default:
    echo '<h1>Search Database!</h1>';
    searchForm();
  
  break;
  
  
  case "search":
    searchForm();
    echo '<h3>Search Results:</h3><br />';
    
    $searchstring = mysql_escape_string($_GET['words']);
    
    $sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchstring}%'";
    
     // echo $sql;
    
    $result = mysql_query($sql) or die ($sql.'<br /><hr /><br />'.mysql_error());
    
    
    while($myrow = mysql_fetch_object($result))
    {
      
      echo '<hr size="1" />';
      echo '<table align="center" cellspacing="0" cellpadding="5">';
      echo'<td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .' </span></td>';  
      echo '</tr>'; 
      echo '</table>'; 
    }
    break;
}

?>

</body>
</html>

 

That should stick with your original switch command although I'm not sure why you used that and get rid of the empty query. I hope it's right anyway

  • Author

thanks

 

but I still get this error, if I search for ben in first name?:

 

SELECT * FROM users WHERE LIKE '%ben%'

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIKE '%ben%'' at line 1

 

 

http://www.ben-smith.net/cms_example/site/...;searchby=fname

 

 

I think there maybe an error in this bit?

 

$sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchstring}%'";

 

 

 

Regarding the switch I was editing part of a tutorial but now have rewrote the code to this:

 

But get this error

 

Parse error: syntax error, unexpected $end in /home/sites/ben-smith.net/public_html/cms_example/site/search4.php on line 94

 

Im quite new to php so any help would be great, I would image when this is fixed I would still get the same error as above, thanks...

 

http://www.ben-smith.net/cms_example/site/search4.php

 

 

<?php 

error_reporting(E_ALL);


/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 


// Create the search function:

function searchForm()
{
 // Re-usable form

 // variable setup for the form.
 $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');
 $searchby = (isset($_GET['searchby'])? NULL : $_GET['searchby']);	  

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in';
 echo '<select name="searchby">';
 echo '<option value="fname"'.$firstn.'>First Name</option>';
 echo '<option value="lname"'.$lastn.'>Last Name</option>';
 echo '<option value="details"'.$details.'>Details</option>';
 echo '<option value="age"'.$age.'>Age</option>';
 echo '<option value="location"'.$location.'>Location</option>';
 echo '<option value="email"'.$email.'>Email</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}


/************************************** END OF FUNCTION *****************************************************/ 


if(isset($_GET['Search'])) { ///// CHECK SEARCH WHEN SUMBMITTED 


/**************************** CHECK SEARCH INPUT SECTIONS *****************************************************/ 

if(empty($_GET['words'])){ /// CHECK SEARCH HAVE BEEN FILLED IN 
   $whatsediterror[1]='<p class="style1"> Please search for something</p>'; 
   $error='false'; 
}  // end if 



} else { 

/**************************** ALL PARTS OF FORM CHECKED *****************************************************/ 


  if (empty($error)){ // IF THERE ARE NO ERRORS THE CARRY ON 

	 $cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');

	echo '<h1>Search Database!</h1>';
  		searchForm();

	if($_GET['Submit']){

	$searchstring = mysql_escape_string($_GET['words']);

  		$sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchstring}%'";

 	// echo $sql;

	$result = mysql_query($sql) or die ($sql.'<br /><hr /><br />'.mysql_error());


while($myrow = mysql_fetch_object($result))
{

  echo '<hr size="1" />';
  echo '<table align="center" cellspacing="0" cellpadding="5">';
  echo'<td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .' </span></td>';  
  echo '</tr>'; 
  echo '</table>'; 
}
break;

} else {

echo '<h1>Search Database!</h1>';
echo "no results found! Try again!";
  		searchForm();
}

?>

ok that was full of problems so try this.

 

<?php 

error_reporting(E_ALL);

/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 


// Create the search function:

function searchForm($select, $searchwords='')
{
 // Re-usable form

 // variable setup for the form.

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in';
 echo '<select name="searchby">';
 foreach ($select as $id => $value)
  echo '<option value="'.$id.'">'.$value.'</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}

/************************************** END OF FUNCTION *****************************************************/ 

$searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : false);
$searchby = (isset($_GET['searchby'])? NULL : mysql_escape_string($_GET['searchby'])); 
$list = array(
			'fname' => 'First Name',
			'lname' => 'Last Name',
			'details' => 'Details',
			'age' => 'Age',
			'location' => 'Location',
			'email' => 'Email'


);
echo '<h1>Search Database!</h1>';
searchForm($list, $searchwords);	   
if(isset($_GET['cmd'])) { ///// CHECK SEARCH WHEN SUMBMITTED 
if($searchwords) /// CHECK SEARCH HAVE BEEN FILLED IN 
   $whatsediterror[1]='<p class="style1"> Please search for something</p>'; 
else 
{ 
	   $sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchwords}%'";
	   $result = mysql_query($sql) or 
	   				die($sql.'<br /><hr /><br />'.mysql_error());
	echo '<hr size="1" />';
	if(mysql_num_rows($result)>0)
	{
		echo '<table align="center" cellspacing="0" cellpadding="5">';		
		while($myrow = mysql_fetch_object($result))
		{
		  echo'<tr><td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .
		  ' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .
		  ' </span></td></tr>'; 
		}
		echo '</table>'; 
	} else {
	echo '<h1>Search Database!</h1>';
	echo "no results found! Try again!";
	}
}
}	
?>

  • Author

Thanks for sorting that out, Never thought about using an array! Im still learning and trying to break things down learning bit by bit.

 

I still get this message thou?

 

Notice: Undefined index: searchby in /home/sites/ben-smith.net/public_html/cms_example/site/search4.php on line 33

 

http://www.ben-smith.net/cms_example/site/search4.php

 

Also if I search for 'ben' none of the information appears?

 

and if a search with a blank field, the error message 'Please search for something' doesnt appear but I get this?

 

SELECT * FROM users WHERE LIKE '%%'

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIKE '%%'' at line 1

 

Thanks for all your help! B)

on line 33 swap

$searchby = (isset($_GET['searchby'])?NULL:mysql_escape_string($_GET['searchby']));

 

to

 

$searchby = (isset($_GET['searchby'])?mysql_escape_string($_GET['searchby']):false);

 

I got the if the wrong way around :-)

  • Author

thanks, but if I search for ben nothing appears and also when pressed with nothing entered, error message doesnt appear?

 

http://www.ben-smith.net/cms_example/site/search4.php

 

??????

 

Do I need to add if(empty) statement to check if the search field has been pressed?

 

<?php 

error_reporting(E_ALL);

/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 


// Create the search function:

function searchForm($select, $searchwords='')
{
 // Re-usable form

 // variable setup for the form.

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in';
 echo '<select name="searchby">';
 foreach ($select as $id => $value)
  echo '<option value="'.$id.'">'.$value.'</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}

/************************************** END OF FUNCTION *****************************************************/ 

$searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : false);
$searchby = (isset($_GET['searchby'])?mysql_escape_string($_GET['searchby']):false);
$list = array(
			'fname' => 'First Name',
			'lname' => 'Last Name',
			'details' => 'Details',
			'age' => 'Age',
			'location' => 'Location',
			'email' => 'Email'


);
echo '<h1>Search Database!</h1>';
searchForm($list, $searchwords);	   
if(isset($_GET['cmd'])) { ///// CHECK SEARCH WHEN SUMBMITTED 
if($searchwords) /// CHECK SEARCH HAVE BEEN FILLED IN 
   $whatsediterror[1]='<p class="style1"> Please search for something</p>'; 
else 
{ 
	   $sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchwords}%'";
	   $result = mysql_query($sql) or 
					   die($sql.'<br /><hr /><br />'.mysql_error());
	echo '<hr size="1" />';
	if(mysql_num_rows($result)>0)
	{
		echo '<table align="center" cellspacing="0" cellpadding="5">';		
		while($myrow = mysql_fetch_object($result))
		{
		  echo'<tr><td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .
		  ' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .
		  ' </span></td></tr>'; 
		}
		echo '</table>'; 
	} else {
	echo '<h1>Search Database!</h1>';
	echo "no results found! Try again!";
	}
}
}	
?>

You don't need the is empty. I found the problem.

 

	if($searchwords) /// CHECK SEARCH HAVE BEEN FILLED IN 
   $whatsediterror[1]='<p class="style1"> Please search for something</p>';

 

should be

 

	if(!$searchwords) /// CHECK SEARCH HAVE BEEN FILLED IN 
   echo '<p class="style1"> Please search for something</p>';

  • Author

Ive added the code and yippe the error message works! :D THANKS!

 

but none of the records are displayed

 

I have 'ben' in 'fname' but the information isnt displayed?

 

<?php 

error_reporting(E_ALL);

/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 


// Create the search function:

function searchForm($select, $searchwords='')
{
 // Re-usable form

 // variable setup for the form.

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in';
 echo '<select name="searchby">';
 foreach ($select as $id => $value)
  echo '<option value="'.$id.'">'.$value.'</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}

/************************************** END OF FUNCTION *****************************************************/ 

$searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : false);
$searchby = (isset($_GET['searchby'])?mysql_escape_string($_GET['searchby']):false);
$list = array(
			'fname' => 'First Name',
			'lname' => 'Last Name',
			'details' => 'Details',
			'age' => 'Age',
			'location' => 'Location',
			'email' => 'Email'


);
echo '<h1>Search Database!</h1>';
searchForm($list, $searchwords);	   
if(isset($_GET['cmd'])) { ///// CHECK SEARCH WHEN SUMBMITTED 
  if(!$searchwords) /// CHECK SEARCH HAVE BEEN FILLED IN 
   echo '<p class="style1"> Please search for something</p>'; 
else 
{ 
	   $sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchwords}%'";
	   $result = mysql_query($sql) or 
					   die($sql.'<br /><hr /><br />'.mysql_error());
	echo '<hr size="1" />';
	if(mysql_num_rows($result)>0)
	{
		echo '<table align="center" cellspacing="0" cellpadding="5">';		
		while($myrow = mysql_fetch_object($result))
		{
		  echo'<tr><td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .
		  ' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .
		  ' </span></td></tr>'; 
		}
		echo '</table>'; 
	} else {
	echo '<h1>Search Database!</h1>';
	echo "no results found! Try again!";
	}
}
}	
?>

gah why are you using fetch object? I totally missed that. use fetch assoc.

 

while($myrow = mysql_fetch_object($result))

 

to

 

while($myrow = mysql_fetch_assoc($result))

 

 

you might want to drop the second appearance of echo '<h1>Search Database!</h1>'; as well :-)

  • Author

Awesome - You the man!

 

Brilliant thanks for you help!

 

Think I was using mysql_fetch_object from another tutorial and missed it! Doh!

 

Thanks again, now going to readup on using arrays - was there any reason you used an array and what are the benefits?

 

 

 

<?php 

error_reporting(E_ALL);

/************************** change to match your connection method ********************/ 

require_once ('../mysql_connect.php'); // Connect to the db. 


// Create the search function:

function searchForm($select, $searchwords='')
{
 // Re-usable form

 // variable setup for the form.

 echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
 echo '<input type="hidden" name="cmd" value="search" />';
 echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
 echo 'in';
 echo '<select name="searchby">';
 foreach ($select as $id => $value)
  echo '<option value="'.$id.'">'.$value.'</option>';
 echo '</select> ';
 echo '<input type="submit" value="Search" />';
 echo '</form>';
}

/************************************** END OF FUNCTION *****************************************************/ 

$searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : false);
$searchby = (isset($_GET['searchby'])?mysql_escape_string($_GET['searchby']):false);
$list = array(
			'fname' => 'First Name',
			'lname' => 'Last Name',
			'details' => 'Details',
			'age' => 'Age',
			'location' => 'Location',
			'email' => 'Email'


);
echo '<h1>Search Database!</h1>';
searchForm($list, $searchwords);	   
if(isset($_GET['cmd'])) { ///// CHECK SEARCH WHEN SUMBMITTED 
  if(!$searchwords) /// CHECK SEARCH HAVE BEEN FILLED IN 
   echo '<p class="style1"> Please search for something</p>'; 
else 
{ 
	   $sql = "SELECT * FROM users WHERE {$searchby} LIKE '%{$searchwords}%'";
	   $result = mysql_query($sql) or 
					   die($sql.'<br /><hr /><br />'.mysql_error());
	echo '<hr size="1" />';
	if(mysql_num_rows($result)>0)
	{
		echo '<table align="center" cellspacing="0" cellpadding="5">';		
		while($myrow = mysql_fetch_assoc($result))
		{
		  echo'<tr><td><span>' .$myrow['fname'] .'</td><td>'. $myrow['lname'] .
		  ' </td><td>'. $myrow['email'] .'</td><td>'. $myrow['location'] .
		  ' </span></td></tr>'; 
		}
		echo '</table>'; 
	} else {
	echo "no results found! Try again!";
	}
}
}	
?>

I tend to write code that's more generic. By using an array like I did it allows you to reuse the function with any array you like and you don't have to alter the function. It also means if you do want to alter that html line it's only one line instead of who knows how many lines. There is no reason specifically to do it. I just prefer it personally.

  • Author

Makes sense and saves alot of time! Do you know any good sites to learn about arrays and how to use them?

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.