Rebekah Rebekah - 1 year ago 86
PHP Question

How to create a search using PHP, mysqli and a html form

I want to create a form which allows the user to type in a search and have it pick up the right values from a database and display them, for some reason I can't get my query to work it just displays "could not search"

Here is my php code


include "connect.php";

$output = '';

if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);

$query = mysqli_query("SELECT * FROM house WHERE town LIKE '%$search%'") or die ("Could not search");
$count = mysqli_num_rows($query);

if($count == 0){
$output = "There was no search results!";


while ($row = mysqli_fetch_array($query)) {

$town = $row ['town'];
$street = $row ['street'];
$bedrooms = $row ['bedrooms'];
$bathroom = $row ['bathrooms'];

$output .='<div> '.$town.''.$street.''.$bedrooms.''.$bathrooms.'</div>';




Here is my form

<form action ="home.php" method = "post">

<input name="search" type="text" size="30" placeholder="Belfast"/>

<input type="submit" value="Search"/>


<?php print ("$output");?>

Answer Source

You're not connecting to your DB in your query:

$query = mysqli_query("SELECT
                      ^ missing connection variable

there is no connection variable (unknown what you are using to connect with)

$query = mysqli_query($connection, "SELECT ...

From the manual

Object oriented style mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Procedural style mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

figuring you are using mysqli_ to connect with. If you're using mysql_ or PDO to connect with, that won't work. Those different MySQL APIs do not intermix with each other.

Plus, instead of or die ("Could not search") do or die(mysqli_error($connection)) to catch any errors, if any.

Add error reporting to the top of your file(s) which will help find errors.

ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

Example mysqli connection:

$connection = mysqli_connect("myhost","myuser","mypassw","mybd") 
                or die("Error " . mysqli_error($connection)); 

For more information, visit:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download