/    Sign up×
Community /Pin to ProfileBookmark

creating a search function on my website

I am trying to create a search function on my website but I am having some troubles. I received a little help but I do not know if it is necessarily the best way.

I have 2 files – search.html and result.php

search.html contains the form with the instructions to run result.php

Here is the code for result.php

[QUOTE]

<?

$name = $_POST[‘name’];

include “DBConnect.inc.php”;

$sql = “SELECT * FROM tablename WHERE column like ‘%.$name.%’ ORDER BY column “;
$res = mysql_query($sql);
$row = mysql_fetch_array($res, MYSQL_ASSOC);

foreach($row as $r)
{
echo “name = $r”;
}
?>

[/QUOTE]

I have been getting this error when i try to run it

” Warning: Invalid argument supplied for foreach() in /home/buf/public_html/Database/Inspection/result.php on line 12″

Any help with this would be much appreciated.

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@sac8513authorOct 21.2007 — anybody??
Copy linkTweet thisAlerts:
@rpcarnellOct 21.2007 — $query = "SELECT * FROM tablinfo WHERE ("; /* Notice that the

query ends here for now*/

foreach($trimmed_array as $kw){


if (!is_array($trimmed))
{
$kw = $trimm = str_replace(",", " ", $kw);
//echo "and kw is ".$kw. " ";
}


if (!is_array($trimmed))
{
$first_trim = str_replace(",", " ", $trimmed_array['0']);
}



if($first_trim != $kw){ //this is used in case there's more than one keyword

$query .= "OR (";}

/*

<-----Notice that we may add an OR to the SQL if there is more than one keyword in the search

*
/

//I use privacy = '0' because some of the users may choose to make their data private.

$query .= "privacy = '0' AND (title LIKE '%$kw%' OR description LIKE '%$kw%' OR keywords LIKE '%$kw%' "; //in SQL, the % is like * for Linux

$query .= "))";

}
Copy linkTweet thisAlerts:
@rpcarnellOct 21.2007 — I hope that jargon helped you somehow. ?


_____________________________________
http://www.carbotek.org
Copy linkTweet thisAlerts:
@sac8513authorOct 21.2007 — I am getting this error


Warning: Invalid argument supplied for foreach() in /home/buf/public_html/Database/Inspection/result.php on line 5

Again I am getting an error in the line that contains the foreach statement. Why is this?
Copy linkTweet thisAlerts:
@rpcarnellOct 23.2007 — This is what came before the code:

$trimmed should be your main worry. $limit is for limiting the output between pages so that you don't have more than, let's say 1000 results in one page but 10, if you make $limit = 10, for each page.

What is $var? $var comes from search.php:

$var = @$_GET['q'] ;

$var = str_replace("", " ", $var);

//trim whitespace from the stored variable

$trimmed = trim($var);

and $trimmed is just $var without spaces. Both of them go to the search function:


function db_Search($trimmed, $limit, $var)

{

if (is_array($trimmed))

{

$trimmed_array = $trimmed;

}

else

{

$trimmed_array = explode(" ",$trimmed);

}

foreach ($trimmed_array as $trimm){

// EDIT HERE and specify your table and field names for the SQL query




if (!is_array($trimmed))
{
$trimm = str_replace(",", " ", $trimm);

}
else
{
$trimm =preg_replace("/@quote@/"," ",$trimm);
$trimm =preg_replace("/@comma@/",",",$trimm);
}


I believe the rest of this is in the previous post. Don't try to copy it all as it is. For this version has a file called keyfixer.php, whose code is long. Keyfixer turns anything between ' ' or " " into a single string the way google does.


--------------------------------------------------
http://www.carbotek.org
Copy linkTweet thisAlerts:
@sac8513authorOct 23.2007 — Thank you. I am not sure though I understand where the table and field name should be inserted
Copy linkTweet thisAlerts:
@rpcarnellOct 23.2007 — Lucky for you I was still logged in when you replied:

<form action="search.php" method="get" name="search">

<input style="border: 1px solid #000; font-size: 1.8em;" name="q" type="text" value="<?php echo $q; ?>" size="15">

<input style="border: 1px solid #000; font-size: 1.4em; padding: 0 0.5em;" name="search" type="submit" value="Buscar">

</form>

Since we are using method="get", search.php will pass the values as part of its url ((notice that the search inout has a name of q)), so you can do this:

@$var = $_GET['q'];

The @ makes it clear to PHP that whatever the server receives must not be altered.
Copy linkTweet thisAlerts:
@sac8513authorOct 23.2007 — Ok understandable but I think I was referring to the portion of code where you stated for the foreach statment to include the table and fieldname. Where in that statement was I including that?
Copy linkTweet thisAlerts:
@sac8513authorOct 23.2007 — Also, i apologize as I am a bit new to this.

You mention not to use certain portion of the code as there is another function running through it. I am not to sure as to how to implement the portion of code in this case.

I appreciate your patience.
Copy linkTweet thisAlerts:
@rpcarnellOct 24.2007 — If you are new to this, you have stumbled into php hell, for creating a search engine with PHP isn't exactly a walk in the park.

Let's see what I can do

This is the script that calls the function:


<?php


//specify how many results to display per page

$limit = 10;

// Get the search variable from URL

$var = @$_GET['q'] ;

$var = str_replace("", " ", $var);

//trim whitespace from the stored variable

$trimmed = trim($var);

//separate key-phrases into an array of keywords with explode


// check for an empty string and display a message.

if ($trimmed == "") {

$resultmsg = "<p><h1>Error!</h1><b> Write at least one word</b></p>" ;

echo $resultmsg;

}

if (strrpos($trimmed, """) > 0)

{

$trimmed = Key_Fixer($trimmed);

foreach ($trimmed as $keywords)
{
$counting++;
$keywords =preg_replace("/@quote@/"," ",$keywords);
$keywords =preg_replace("/@comma@/",",",$keywords);
$counting++;
}

}

//**********************************************

//The function that does the searching is right below

//*
**
******************************************

db_Search($trimmed, $limit, $var);


?>
Copy linkTweet thisAlerts:
@rpcarnellOct 24.2007 — <?php

include_once("seares.php");

function db_Search($trimmed, $limit, $var)

{

if (is_array($trimmed))

{

$trimmed_array = $trimmed;

}

else

{

$trimmed_array = explode(" ",$trimmed);

}

foreach ($trimmed_array as $trimm){

// EDIT HERE and specify your table and field names for the SQL query




if (!is_array($trimmed))
{
$trimm = str_replace(",", " ", $trimm);

}
else
{
$trimm =preg_replace("/@quote@/"," ",$trimm);
$trimm =preg_replace("/@comma@/",",",$trimm);
}

$query = "SELECT * FROM 'insert_table_name_here' WHERE (";

foreach($trimmed_array as $kw){


if (!is_array($trimmed))
{
$kw = $trimm = str_replace(",", " ", $kw);

}
else
{
$kw =preg_replace("/@quote@/"," ",$kw);
$kw =preg_replace("/@comma@/",",",$kw);
}

if (!is_array($trimmed))
{
$first_trim = str_replace(",", " ", $trimmed_array['0']);

}
else
{
$first_trim = preg_replace("/@quote@/"," ",$trimmed_array['0']);
$first_trim = preg_replace("/@comma@/",",",$first_trim);
}


if($first_trim != $kw){ //this is used in case there's more than one keyword

$query .= "OR (";

}

$query .= "privacy = '0' AND (title LIKE '%$kw%' OR description LIKE '%$kw%' OR keywords LIKE '%$kw%' "; //% is like the Linux *

$query .= "))";

}

//*****************************************

// Execute the query to get number of rows that contain search kewords

$numresults= @mysql_query ($query);

$row_num_links_main = @mysql_num_rows ($numresults);

// next determine if 's' has been passed to script, if not use 0.
// 's' is a variable that gets set as we navigate the search result pages.
$s = $_GET['s'];
$row_num_links_main<br />";
if (empty($s)) {
$s=0;
}

// now let's get results.
$query .= " LIMIT $s,$limit" ;
$numresults = @mysql_query ($query) or die (COUN_EXEC);
$row= @mysql_fetch_array ($numresults);

do{
$adid_array[] = $row['id'];
}while( $row= @mysql_fetch_array($numresults));

} //end foreach






if($row_num_links_main == 0){

$resultmsg = "<p>".RES_4.$trimmed."</p><p>".SEAR_BUT."</p>" ;

}

//delete duplicate record id's from the array. To do this we will use array_unique function

$tmparr = array_unique($adid_array); // If, for example, $adid_array has green twice, the second green will be deleted.

$i=0;

foreach ($tmparr as $v) {

$newarr[$i] = $v; //Now $newarr is an array with ascending values in $i

$i++;

}



// now you can display the results returned. But first we will display the search form on the top of the page

if ($trimm != "")

{

Search_Res($result_msg, $s, $newarr, $var, $trimm, $limit, $row_num_links_main);

}



} ?>
Copy linkTweet thisAlerts:
@rpcarnellOct 24.2007 — Here is another function you ma need:

<?php

function Search_Res($resultmsg, $s, $newarr, $var, $trimm, $limit, $row_num_links_main)

{

if( isset ($resultmsg)){

echo YOU_SEAR.$resultmsg;

exit();

} else{

echo RES_SE4."<strong>" . $var ."</strong>";

}

$counting_links = 1 + $s;

if ($row_num_links_main != "")

{

foreach($newarr as $value){

// EDIT HERE and specify your table and field names for the SQL query

$query_value = "SELECT * FROM 'insert_table_name_here' WHERE id = '$value'";
$num_value= @mysql_query ($query_value);
$row_linkcat= @mysql_fetch_array ($num_value);
$row_num_links= @mysql_num_rows ($num_value);




//now let's make the keywods bold. To do that we will use preg_replace function.

//Replace field

$titlehigh = preg_replace ( "'($var)'si" , "<b>$var</b>" , $row_linkcat[ 'title' ] );

$linkhigh = preg_replace ( "'($var)'si" , "<b>$var</b>" , $row_linkcat[ 'url' ] );

$linkdesc = preg_replace ( "'($var)'si" , "<b> $var</b>" , $row_linkcat[ 'description' ] );


if($trimm != 'b' ){
$titlehigh = preg_replace( "'($trimm)'si" , "<b>$trimm</b>" , $titlehigh);
$linkhigh = preg_replace( "'($trimm)'si" , "<b>$trimm</b>" , $linkhigh);
$linkdesc = preg_replace( "'($trimm)'si" , "<b>$trimm</b>" , $linkdesc);
$file_name = $row_linkcat[ 'filename' ];
}


//end highlight

echo "<p>";


$next_assur = $counting_links - $s;

$counting_links++;
echo "<br /><u><strong><a href='http://".$row_linkcat[ 'url' ]."/".$row_linkcat[ 'filename' ]."'>".$row_linkcat[ 'title' ]."</a></strong></u><br />";
echo $linkdesc."...</p>";
echo "<p style='color: #f00;'>".$linkhigh."</p><br />";




//end foreach $trimmed_array

}

}

else

{

echo "<br /><br /><h2>".SEAR_BUT."</h2>";

}


if($row_num_links_main > $limit)
{
echo "<table style='text-align: center; margin: auto;' cellspacing='10px'><tr>";

// next we need to do the links to other search result pages

$argh = $counting_links - 1;

if ($s>=1) { // do not display previous link if 's' is '0'

$prevs=($s-$limit);

echo "<td><a href='$PHP_SELF?s=$prevs&q=$var&catid=$catid'> << ".PREVIOUS."</a></td>";

}

// check to see if last page

$slimit =$s+$limit;

if ($limit < $row_num_links_main)

{

$page_number = ($s/$limit) + 1;

echo "<td><b>".PAGE." $page_number</b></td>";

}

if (!($slimit >= $row_num_links_main) && $row_num_links_main!=1 && ($argh - $s) == $limit) {
// not last page so display next link
$n=$s+$limit;
echo "<td><a href='$PHP_SELF?s=$n&q=$var&catid=$catid'> ".NEXT." >> </a></td>";
}
echo "</tr></table>";
}


}

?>
Copy linkTweet thisAlerts:
@rpcarnellOct 24.2007 — This function separates keywords if they have " "'s between them. That means something like this "People are cruel" becomes one keyword to search: People are cruel

And if you type "people are cruel" PHP language

You will get three keywords:

(1) PHP

(2) language

(3) People are cruel

<?php

function Key_Fixer($str)

{

$counter = strlen($str);

$o = 0;

for($i=0; $i<=$counter; $i++){

if($str[$i]=='"') //We use the length of the string to figure out where the "'s are located.

{

$output[$o] = $i; //Each position-value of " becomes a value in the output array.

$o++;

}

}

$output2 = count($output); //now we determine how many occurrences of " there are.

$L = 0;

$LL = 1;

$ui = 1;

foreach ($output as $tryit)

{

$exp[$L] = $output[$L];

if ($LL == 2 && $ui == 1)

{

$eye[$L] = substr($str, $output[$L - 1] +1, ($output[$L] - $output[$L - 1] -1)); //We take every phrase inside "" out of the string.

$LL = 1;

$ui = 0;

}

if ($ui == 0 && $LL ==2) //and using $ui, we make sure words between quotes aren't included ---> "Quote 1" extra words "Quote 2"

{

$ui = 1;

$LL = $LL - 1;

}

$L++;

$LL++;

}

$T = 0;

$itt = explode('"', $str); //All words are separated by "'s, even the ones that aren't quotes.

$str2 = "";

foreach ($itt as $tryit)

{

$kw[$T] = $tryit;
if ($kw[$T] == $eye[$T])
{

$kw[$T]= preg_replace("/(s)+/","@quote@",$kw[$T]); //The quotes will be @quote@ between their spaces.

$kw[$T]= preg_replace("/(,)+/","@comma@",$kw[$T]);

}
$str2 .=$kw[$T]; //$str2 becomes the new version of the original $str string.
$T++;


}

$str = $str2; //$str has now been altered.

$str2 = preg_split("/[s,]+/", $str, -1, PREG_SPLIT_NO_EMPTY); //We use commas, spaces, /r, /t, etc to split the string

$counting = 1;

return $str2;



}

?>
Copy linkTweet thisAlerts:
@bokehOct 24.2007 — What a mess! When posting code in the forum use the [B]&#91;PHP&#93;&#91;/PHP&#93;[/B] tags around your code so it is displayed in a readable form.
Copy linkTweet thisAlerts:
@rpcarnellOct 24.2007 — You think it is a mess? Imagine how long it'd take me to explain it all, as I took two different tutorials and put them together to come out with all that code.
Copy linkTweet thisAlerts:
@bokehOct 24.2007 — You think it is a mess? Imagine how long it'd take me to explain it all, as I took two different tutorials and put them together to come out with all that code.[/QUOTE]However much effort you make it is all for nothing if you don't use the forum's built in code formatting as no one will bother reading it.
Copy linkTweet thisAlerts:
@rpcarnellOct 25.2007 — In this case, it is just a matter of copy/paste mostly.?
Copy linkTweet thisAlerts:
@bokehOct 25.2007 — In this case, it is just a matter of copy/paste mostly.?[/QUOTE]Oh dear! Haven't you ever wondered why most people's code is nicely highlighted in the forum and yours is not? It's because they use the PHP code tags.
Copy linkTweet thisAlerts:
@sac8513authorOct 28.2007 — nonetheless, i would really like some help with this code. I am really just trying to have a database store about 500 store name and want to create a search box to search through those name after typing in the name of the store...
×

Success!

Help @sac8513 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...