Jump to content

PHP search box


Renato

Recommended Posts

I'm creating search box, to search users on my database

 

this is the form

<form action='' method='get' >
    <input type='text' name='search' />
    <input type='submit' value='search'/>	<br/>
</form>

php

<?php
$search = $_GET['search'];

$terms = explode( " ", $search);
$query = "SELECT * FROM login WHERE";

foreach ($terms as $each) {
	$i++;
	
	if ($i==0)
		$query .= "username like '%$each%' ";
	else
		$query .= "OR username like '%$each%' ";
	}
	mysql_connect("localhost", "renatov_admin", "password1!") or die (mysql_error());
	mysql_select_db("renatov_database") or die ("could not find bd!");
	
	$squery = mysql_query($query);
	$numrows = mysql_num_rows($query);
	if ($numrows > 0){
	
	while($row = mysql_fetch_assoc($query)){
			$username = $row['username'];
			$nationality = $row['nationality'];
			$age = $row['age'];
			$search = $row['search'];
			
			
			echo "<h2><a href='$link'>$username</a> </h2>";
		
		}
	
	}
	else	
		echo "No results found for \"<b>$search</b> \"";
	
	mysql_close();
?>

it comes with error:

Warning: mysql_num_rows() expects parameter 1 to be resource, string given

 

Is always "No result found for"

Can someone tell me where I'm doing wrong?

 

Link to comment
https://forums.phpfreaks.com/topic/293697-php-search-box/
Share on other sites

Then most likely your query is failing, but you never check for that and just assume it runs .  See how they do it in http://php.net/manual/en/function.mysql-query.php in the first example labeled "Example #1 invalid query"

 

My guess is because you don't have a space after the WHERE and when you add to the query.

 

As a side note, mysql is deprecated and will be removed from PHP in the future. You should be using PDO or mysqli if you don't want to have to rewrite all of this for newer upcoming versions of PHP. You're not doing yourself any favors by using something that is already deprecated.

Link to comment
https://forums.phpfreaks.com/topic/293697-php-search-box/#findComment-1501874
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.