简体   繁体   中英

Simple search bar returns with no results using MySQL

I have created a simple search bar in my website, when I try to get a result it tell me that there are no results, I think I have a mistake in my code, I have been going at it for quite a while but no luck, bellow I will post the HTML, the confing.php and the search.php .

HTMML search:

<form id="form" name="search" method="post" action="search.php">
<input type="text" name="search" id="search" placeholder="search..." />
<button class="w3-button w3-small w3-ripple" type="submit" name="submit"     value=""><i class="fa fa-search"></i></button>
</form>

Eventhough is connecting fine here is the config.php

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'BimL1st!');
define('DB_DATABASE', 'myDB');
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DBPASSWORD, DB_DATABASE);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

here is the search.php

require 'config.php';

$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DBPASSWORD, DB_DATABASE);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected";

$search = "";

if ($_SERVER["REQUEST_METHOD"] == "POST"){
$search = test_input($_POST['search']);
} 

function test_input ($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

$min_length = 0;

if (strlen($data) >= $min_length) {

$sql = "SELECT * FROM Registry WHERE Business_Name like '%$data%' OR Business_Address like '%$data%' 
OR Name like '%$data%' OR phone like '%$data%' OR Email like '%$data%' OR Category like '%$data%'
OR Recomend like '%$data%' OR Services like '%$data%' OR Expertise like '%$data%'";
echo '<br>';
echo "Search completed";
echo '<br>';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Business Name: " . $row["Business_Name"]. "Business Address:  " . $row["Business_Address"]. 
        "Person in charge: " . $row["Name"]. "Phone number: " .$row["phone"]. "Email: " .$row["Email"].
        "Business Category: " .$row["Category"]. "Recomended by: " .$row["Recomend"]. "Services Rendered: " .$row["Services"]. 
        "What sets us appart: " .$row["Expertise"]. "<br>";
    }
} else {
    echo "0 Results";
}
} else {
echo "invalid length";
}

It seem odd to me in your $sql declaration LIKE '%$data%'

Perhaps you can try to concat them LIKE '%".$data."%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM