user3417199
user3417199

Reputation: 19

PHP Search Script not working

I am trying to run a simple PHP search script that will show look through my mySQL database and present the results on a separate page that I've created. When I run the code, my results don't show up. Can someone please help me?? This is the code that i'm currently using:

<?php

    error_reporting(E_A`enter code here`LL);
    ini_set('display_errors', 1);

        $k = $_GET['k'];
        $terms = explode(" ", $k);
        $query = "SELECT * FROM search WHERE ";

        $i = 0;
        foreach ($terms as $each){
            $i++; 

            if ($i == 1) 
            {
                $query .= "keywords LIKE '%$each%' ";
            }           
            else
            {
                $query .= "OR keywords LIKE '%$each%' ";
            }   
    }

        // connect
        mysql_connect("josetogbecom.fatcowmysql.com","username","password");
        mysql_select_db("gff_hff6a144eg");

        $query = mysql_query($query);
        $numrows = mysql_num_rows($query);
        if ($numrows > 0){

            while ($row = mysql_fetch_assoc($query)){
                $id = $row['id'];
                $title = $row['title'];
                $description = $row['description'];
                $keywords = $row['keywords'];
                $link = $row['link'];

                echo "<h2><a href='$link'>$title</a></h2>
                $description<br /><br />";
            }   

        }
        else 
        {
            echo "No Search Results Were Found for \"<b>$k<b>\"";
        }


        // disconnect
        mysql_close();

    ?>

Thanks in advance!

Upvotes: 0

Views: 131

Answers (2)

user997172
user997172

Reputation:

Bug at this line:

echo "No Search Results Were Found for \"<b>$k<b>/"";

Should be:

echo "No Search Results Were Found for \"<b>$k<b>\"";

Bug at this line:

mysql close();

Should be:

mysql_close();

Bug at this line:

$i++;

You should always initialize your variables, like this:

$i = 0;
foreach ($terms as $each){
    $i++;

    if ($i == 1)
        $query .= "keywords LIKE '$each%' ";
    else
        $query .= "OR keywords LIKE '$each%' ";
} 

If the script still doesn't work after correcting these two bugs, add to the beginning of the script these 2 lines and tell us what you see:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Upvotes: 1

Rubensito
Rubensito

Reputation: 102

Check if your $i counter var is set to $i=0 before foreach loop

Upvotes: 1

Related Questions