user3173250
user3173250

Reputation: 1

trying to search through sql data shown in php, not working

Hi I have a SQL database which contains information about properties. Above this I have a search button which searches the propertyLocation field to display relevant ones.

Example:

Property ID 1, 5 Bedroom House, London
Property ID 2, 3 Bedroom House, Scotland
Property ID 3, 2 Bedroom Flat, Cardiff.

At the top all i'm trying to do is put a search in which if the user types "london" only property ID 1 will be shown. I cannot seem to get it to work! My code is as follows:

Displaying the properties and search box:

<table id="propertyTable">

    <form method="post" action="search.php">
        <input type="text" name="search" />
        <input type="submit" name="submit" value="   Search   ">
    </form>

    <th>Property ID</th>
    <th>Property Name</th>
<?php   
        $result = mysql_query("SELECT * FROM Property");
        while ($row = mysql_fetch_array($result))
            {
                $pID = $row['pID'];
                $pLocation = $row['pLocation'];

                echo "<tr data-row='$pID'><td>$pID</td>";
                echo "<td>".$pID."</td>";
                echo "<td>".$pLocation."</td>";
            }
?>
</table>

Search.php code:

<?php

$sql="SELECT * FROM Property
WHERE pLocation like '$search%'";

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


while ($row=mysql_fetch_array($result))
{
$pID=$row["pID"];
$pLocation=$row["pLocation"];
}
?>

Please note I am connecting to my DB at the top. The first form does display the properties however, search just does not work.

Any help would be greatly appreciated!

Upvotes: 0

Views: 98

Answers (2)

Digital Chris
Digital Chris

Reputation: 6202

You need to get your $search var out of the $_POST array:

$search = $_POST['search'];

edit:

Saw your second error about DB. You said: "Please note I am connecting to my DB at the top. " but if you are getting $db undefined, there is an issue with this. Maybe follow the syntax on your other page and use the assumed connection like:

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

On the first page there is output echoed. You need to mimic that on your search results:

            $pID = $row['pID'];
            $pLocation = $row['pLocation'];

            echo "<tr data-row='$pID'>";
            echo "<td>".$pID."</td>";
            echo "<td>".$pLocation."</td></tr>";

I tried to fix some of the wonky table structure; the first page seemed to output one long row?

Upvotes: 1

Deepika Janiyani
Deepika Janiyani

Reputation: 1477

Try the following, i.e. initialize the $search variable with the POST value

 <?php

 $search  = trim($_POST['search']);

 $sql="SELECT * FROM Property
 WHERE pLocation like '$search%'";

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


 while ($row=mysql_fetch_array($result))
 {
    $pID=$row["pID"];
    $pLocation=$row["pLocation"];
  }
 ?>

Upvotes: 0

Related Questions